我有一个使用MVC Web API 2的服务的WPF应用程序。使用HTTPClient调用异步方法(如PostAsync和GetAsync)创建RestClient包装器。对于前我的POST方法包装将如下所示:使用c#调用Web API 2方法HTTPClient使用CLR存储过程
using (var client = new HttpClient(new HttpClientHandler()
{ AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }))
{
var content = new FormUrlEncodedContent(postObject);
SetupClient(client, methodName, apiUrl, postObject, headerContent);
if (apiKey != null && appId != null)
await SetAuthorizationHeader(client, methodName, apiUrl, appId, apiKey, content).ConfigureAwait(false);
using (HttpResponseMessage response = Task.Run(() => client.PostAsync(apiUrl, content)).Result)
{
response.EnsureSuccessStatusCode();
using (HttpContent httpContent = response.Content)
{
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsAsync<T>().Result;
}
}
}
}
哪个工作正常。现在我正尝试通过创建SQL Server数据库项目来通过C#CLR存储过程调用一些API调用。
C#CLR存储过程会像:
[Microsoft.SqlServer.Server.SqlProcedure]
public static void SQLRestClient(SqlString weburl, SqlString postBody, SqlString appIdString, SqlString apiKeyString, SecureString baseAddress, out SqlString returnval)
{
string apiUrl = Convert.ToString(weburl);
string baseAddressString = Convert.ToString(baseAddress);
string result = string.Empty;
var appId = ConvertToSecureString(Convert.ToString(appIdString));
var apiKey = ConvertToSecureString(Convert.ToString(apiKeyString));
try
{
string methodName = HttpMethod.Post.Method.ToUpper();
using (var client = new HttpClient(new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
}))
{
var content = new FormUrlEncodedContent(postObject);
SetupClient(client, methodName, apiUrl, postObject, headerContent);
if (apiKey != null && appId != null)
await SetAuthorizationHeader(client, methodName, apiUrl, appId, apiKey, content).ConfigureAwait(false);
using (HttpResponseMessage response = Task.Run(() => client.PostAsync(apiUrl, content)).Result)
{
response.EnsureSuccessStatusCode();
using (HttpContent httpContent = response.Content)
{
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync();
}
}
}
}
}
catch (Exception ex)
{
SqlContext.Pipe.Send(ex.Message.ToString());
}
returnval = result;
}
当我尝试生成此过程中我得到建立自己的错误的DLL。 它,因为编译器不能识别集引用如
System.Net.Http.dll
当我通过这个线程
Sending HTTP POST request from SQL Server 2012 or SQL CLR C#
我找到了解决办法了使用HttpWebRequest而不是HttpClient。由于我一直在我的应用程序中使用HttpClient,我不想切换到HttpWebRequest。
任何人都可以提出任何其他方式,以便我可以通过使用HttpClient生成CLR存储过程DLL。任何帮助将不胜感激,并提前致谢。