我在点击按钮时从ASP.NET页面调用了Web API,如下所示。
这完全正常工作虽然我已经读过它会创建死锁,因为它不是async
(由于在行.Result
中使用client.PostAsJsonAsync(url, sd).Result;
)
请建议更新此代码的最佳方式。
private void CallApi(SurveyData sd)
{
using (var client = new HttpClient())
{
string url = ConfigurationManager.AppSettings.Get("url");
client.DefaultRequestHeaders.Accept.Clear();
var response = client.PostAsJsonAsync(url, sd).Result;
if (response.IsSuccessStatusCode)
{
Response.Write("Success");
}
else
{
Response.Write(response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
}
答案 0 :(得分:1)
如果您不想使用异步,那么您可以使用WebClient而不是HttpClient。
WebClient client = new WebClient();
string response = client.UploadString(RequestUrl, "POST", data);
答案 1 :(得分:0)
您可以将该方法重写为async
方法(在这种情况下,我建议提供string
的返回类型):
private async Task<string> CallApi(SurveyData sd)
{
string result = String.Empty;
using (var client = new HttpClient())
{
string url = ConfigurationManager.AppSettings["url"];
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.PostAsJsonAsync(url, sd);
if (response.IsSuccessStatusCode)
{
result = "Success";
}
else
{
result = response.StatusCode + " : Message - " + response.ReasonPhrase;
}
}
return result;
}
然后您还可以await
此次通话的结果:
Response.Write(await CallApi(sd));
虽然需要在另一个async
方法中进行调用。否则你必须Response.Write(CallApi(sd).Result);
,我不知道你是否会看到性能有了显着改善。
答案 2 :(得分:0)
您可以尝试使用此方法
public async Task<HttpResponseMessage> GetHttpClientResult<T>(string baseUrl, string url, T requestParam, bool isExternalLink = false,
string acceptMediaVerb = "application/json", HttpMethod requestMethod = null)
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
if (!isExternalLink)
{
client.BaseAddress = new Uri(baseUrl);
}
if (!string.IsNullOrEmpty(acceptMediaVerb))
{
if (acceptMediaVerb == "application/json")
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (requestMethod == HttpMethod.Get || requestMethod == null)
{
response = client.GetAsync(url).Result;
}
else if (requestMethod == HttpMethod.Post)
{
response = await client.PostAsJsonAsync(url, requestParam);
}
}
}
var context = new HttpContextWrapper(HttpContext.Current);
HttpRequestBase request = context.Request;
return response;
}
catch
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
}
这开始写为通用方法,用于处理api方法,其中包含在应用程序本身或任何外部Web请求中配置的基本URL