2016-05-11 15 views
7

Bir düğmeyle Web API'sini ASP.NET sayfasından aradım. Bu mükemmel bir yerlerde okudum olsa async değil gibi kilitlenme yaratacaktır iyi çalışıyor (hat client.PostAsJsonAsync(url, sd).Result; içinde .Result kullanımı nedeniyle)Web API'sini Arayın Uygulamadan

bu kodu güncellemek için en iyi yolu önerin.

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

yapılandırılan bir taban url ile API yöntemlerini ele almak genel bir yöntem olarak yazmaya başlamış olup

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

bu yöntemle deneyebilirsiniz Evet, satır, var response = client.PostAsJsonAsync (url, sd) .Sonuç; cevap beklemek zorunda. Web sunucunuzda async denetleyici seçeneğini kullanabilirsiniz. – Saadi

+0

Emin değilim, ama eğer 'CallApi' yöntemini 'async' yaparsanız ve bu yöntemi kullanırken 'bekle' seçeneğini kullanırsanız ne olur? – Raghuveer

+2

MVC değilse, yöntem zaman uyumsuz hale getirilebilir ve istemci.PostAsJsonAsync beklenebilir. Genelde olsa da (anladığım kadarıyla, geçersiz yöntemleri async olarak işaretlemek için kötü bir uygulama). – Tim

cevap

1

Zaman uyumsuz kullanmak istemiyorsanız, HttpClient yerine WebClient kullanabilirsiniz.

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

Sen (ben string bir dönüş türü sağlayarak öneririm bu durumda) bir async yöntemi olarak yöntem yazabilirsiniz: Sonra

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

yapabildin da await bu çağrının sonuçları:

Response.Write(await CallApi(sd)); 

çağrı gerekir rağmen

başka async yöntemi içinde yapılacak. Aksi halde, 'u yapmanız gerekecek ve o zaman performansta önemli bir gelişme olup olmadığını bilmiyorum.

+0

Bir "async" yöntemi bir "string" döndüremiyor, bunun yerine bir Görev 'döndürmelidir. Lütfen cevabınızdaki dönüş türünü düzeltin. –

+0

@FedericoDipuma - Doğru. Yakalama için teşekkürler :) – Tim

0

Bu başvurunuzun kendisi veya herhangi bir harici web isteği