I want to get some data from a web api
, and I write this code:
var response = await Client.GetAsync("https://SomeURL/Action");
when I run this code in button click I get this error:
Access to fetch at 'https://SomeURL/Action' from origin 'http://OtherURL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
so for solve this problem I was trying to add this code in program.cs
in Blazor
application:
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("https://SomeURL/")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
but Services
does not contain a definition for AddCors
. How can I solve this issue? Thanks
Edit 1)
I create very simple built-in web api:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
and I get the result:
When I want to connect to this web api I get CORS
error. and I change program.cs
in Web API project:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
builder.WithOrigins("http://localhost:5179")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
var app = builder.Build();
app.UseCors();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
and in Blazor
project I have this:
@page "/counter"
@inject HttpClient Client
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private async Task IncrementCount()
{
currentCount++;
var response = await Client.GetAsync("https://localhost:7229/weatherforecast");
}
}
Please help me to resolve the problem.
This works for me:
add app.UseCors();
with policy name this way:
app.UseHttpsRedirection();
app.UseCors("CorsPolicy");
app.UseAuthorization();