简体   繁体   中英

Call Web API From Application

I have called Web API from ASP.NET page on a button click as below. This is perfectly working fine though I have read somewhere it will create deadlock as it is not async (due to use of .Result in line client.PostAsJsonAsync(url, sd).Result; )

Please suggest best way to update this code.

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);
        }
    }
}

If you don't want to use async then you could use WebClient instead of HttpClient.

WebClient client = new WebClient();
string response = client.UploadString(RequestUrl, "POST", data);

You could rewrite the method as an async method (in which case I'd suggest providing a return type of 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;
}

Then you could also await the results of this call:

Response.Write(await CallApi(sd));

Though the call would need to be made from within another async method. Otherwise you'd have to do Response.Write(CallApi(sd).Result); , and I don't know if you'd see a significant improvement in performance then.

You may try with this method

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);
            }
        }

This is started to write as a generic method to handle api methods with a base url configured in your application itself or any external web request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM