【发布时间】:2017-06-14 08:53:49
【问题描述】:
我有一个 WPF 应用程序,它使用 MVC Web API 2 的服务。使用 HTTPClient 创建了 RestClient 包装器来调用 PostAsync 和 GetAsync 等异步方法。例如,我的 POST 方法包装器如下:
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。任何帮助将不胜感激,并提前致谢。
【问题讨论】:
标签: c# .net sql-server asp.net-web-api sqlclr