shanthu
shanthu

Reputation: 1

Blazor application is getting Forbidden (403) when calling an external API (which works fine in PostMan)

Visual Studio 2019, .NET 3.0 preview, Created a blazor application. Trying to get weather data from https://api.weather.gov/gridpoints/ALY/59,14/forecast. I am using HttpClient in C#. This is getting forbidden (403) response

Tried to add CORS policty

private async Task<IWeatherDotGovForecast> RetrieveForecast()
        {
            string url = @"https://api.weather.gov/gridpoints/ALY/59,14/forecast";
            var response = await _httpClient.GetAsync(url);

            if (response != null)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<WeatherDotGovForecast>(jsonString);
            }

            //return await _httpClient.GetJsonAsync<WeatherDotGovForecast>
            //  ("https://api.weather.gov/gridpoints/ALY/59,14/forecast");

            return null;
        }

I expected JSON data from https://api.weather.gov/gridpoints/ALY/59,14/forecast

Instead, I am getting Forbidden (403) status code

Upvotes: 0

Views: 1953

Answers (1)

Postlagerkarte
Postlagerkarte

Reputation: 7117

Your problem is not related to Blazor but weather.gov requires a User-Agent header in any HTTP request.

Applications accessing resources on weather.gov now need to provide a User-Agent header in any HTTP request. Requests without a user agent are automatically blocked. We have implemented this usage policy due to a small number of clients utilizing resources far in excess of what most would consider reasonable.

Use something like this:

 var _httpClient = new HttpClient();
 string url = @"https://api.weather.gov/gridpoints/ALY/59,14/forecast";
 _httpClient.DefaultRequestHeaders.Add("User-Agent", "posterlagerkarte");
 var response = await _httpClient.GetAsync(url);

Upvotes: 2

Related Questions