简体   繁体   English

C#Web API调用

[英]C# Web API call

This is the first time i've tried making a call to an API and I'm struggling a little. 这是我第一次尝试对API进行调用,但是我有点挣扎。 I keep getting back my error message, I plan on using the json response to populate my object. 我一直在找回错误消息,我打算使用json响应来填充对象。 The OMDB api instructions are here (not helpful though): http://www.omdbapi.com/ OMDB api说明在此处(尽管无济于事): http ://www.omdbapi.com/

private static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://www.omdbapi.com/?");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("t=Captain+Phillips&r=json").Result;

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Success");
        }
        else
        {
            Console.WriteLine("Error with feed");
        }
    }
}

You have placed the question mark ( ? ) on the wrong place. 您将问号( ? )放在错误的位置。 Try like this: 尝试这样:

private static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://www.omdbapi.com");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("?t=Captain+Phillips&r=json");

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Success");
        }
        else
        {
            Console.WriteLine("Error with feed");
        }
    }
}

Notice that the question mark is here: 注意,问号在这里:

HttpResponseMessage response = await client.GetAsync("?t=Captain+Phillips&r=json");

and not on the base url as you placed it. 而不是放置在基本网址上。

Also in order to properly write your asynchronous method you need to await on it inside and not be eagerly calling the .Result property which of course is a blocking operation. 同样,为了正确地编写异步方法,您需要在内部await它,而不必急于调用.Result属性,这当然是一个阻塞操作。

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

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