-1

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

-1

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.

  • The web site specifies this here: https://weather-gov.github.io/api/general-faqs#im-getting-a-403-forbiddenaccess-denied-error-from-the-api – Dave1952 Jul 11 '23 at 19:22
-1

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; foo@bar.baz)");