简体   繁体   English

调用Web API

[英]Calling web API

I am trying to call a web api and I want to see what response I get. 我正在尝试调用网络api,我想查看得到的响应。 WOuld it be 200, 204 or 500. 是200、204还是500。

I am trying it fot thr first time. 我正在第一次尝试。

public void foo()
{
  RunAsync(); // dont know what it return type will be
}


static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:9000/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync("pid=23&lang=en-us");

            }
        }

Here, the code stops on the last line. 在这里,代码在最后一行停止。 How can I do that ? 我怎样才能做到这一点 ?

You can use the StatusCode property of your HttpResponseMessage. 您可以使用HttpResponseMessage的StatusCode属性。

HttpResponseMessage response = await client.GetAsync("pid=23&lang=en-us");
if (response.IsSuccessStatusCode)
{
    //was success
    var result = await response.Content.ReadAsStringAsync();     
    //checck result string now
   //you can also deserialize the response to your custom type if needed.
}
else
{
  var statusCode = response.StatusCode;
  //do something with this
}

Here is the official documentation of HttpStatusCode enumeration which gives you a complete list of possible status code values. 是HttpStatusCode枚举的官方文档,该文档为您提供了可能的状态代码值的完整列表。

Since your method returns a Task, you should await it when you call it. 由于您的方法返回一个Task,因此您应在调用它时等待它。

public async Task foo()
{    
   await RunAsync(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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