从应用程序调用Web API

Jig*_*hah 7 c# asp.net-web-api

我通过单击按钮从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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Aam*_*ood 1

如果您不想使用异步,那么您可以使用 WebClient 而不是 HttpClient。

WebClient client = new WebClient();
string response = client.UploadString(RequestUrl, "POST", data);
Run Code Online (Sandbox Code Playgroud)