skip to Main Content

I have no trouble accessing the https://api.weather.gov/ API using Postman. But when I write simple .NET C# console app using Visual Studio 2017 using the suggested code snippet from Postman, I get this error. I am running both Postman and Visual Studio on a corporate VDI. How can I get it to work on Visual Studio? This is my code:

    class Program
    {
        static void Main()
        {
            RunAsync().GetAwaiter().GetResult();
        }

        static async Task RunAsync()
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, "https://api.weather.gov/gridpoints/IND/59,75/forecast");

            try
            {
                var response = await client.SendAsync(request);
                var statusCode = response.StatusCode.ToString();
                //response.EnsureSuccessStatusCode();
                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine($"Status code = ", statusCode);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
        }

2

Answers


  1. Chosen as BEST ANSWER

    The solution was to add a User-Agent header key. The code I added was:

                request.Headers.Add("User-Agent", "Testing API Client");
    

    For some reason, Postman works without it.


  2. This error was answered in the post: Current Observation feed from weather.gov forbidden (403)

    You need add the following code after declare the request:

    request.Headers.Add("User-Agent", "MyApplication/v1.0 (http://foo.bar.baz; [email protected])");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search