CORS error while fetching data from asp.net core web api

mehmood tekfirst 771 Reputation points
2022-05-11T07:21:50.293+00:00

Hi,

I am trying to access my asp.net core Web API from fetch in ReactJS.

But I am getting the CORS error.

see my components and error below

--- Program.cs ----  

var builder = WebApplication.CreateBuilder(args);  
  
  
builder.Services.AddCors(options =>  
{  
    options.AddPolicy(name: "MyPolicy",  
                policy =>  
                {  
                    policy.WithOrigins("https://localhost:7260/","https://localhost:44485/")  
                            .WithMethods("POST", "PUT", "DELETE", "GET");  
                });  
});  
  
  
// Add services to the container.  
  
builder.Services.AddControllersWithViews();  
  
  
#region Session/Cache Management  
    builder.Services.AddDistributedMemoryCache();  
  
    builder.Services.AddSession(options =>  
    {  
        options.IdleTimeout = TimeSpan.FromSeconds(10);  
        options.Cookie.HttpOnly = true;  
        options.Cookie.IsEssential = true;  
    });  
#endregion  
  
#region Database Configurations  
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");       
    builder.Services.AddSqlServer<CarRentalContext>(connectionString);  
    builder.Services.AddScoped<IFranchiseRespository, FranchiseRespository>();  
    builder.Services.AddScoped<IEnquiryRepository, EnquiryRepository>();  
    builder.Services.AddScoped<ISearchRepository, SearchRepository>();  
#endregion  
  
var app = builder.Build();  
  
// Configure the HTTP request pipeline.  
if (!app.Environment.IsDevelopment())  
{  
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
    app.UseHsts();  
}  
  
app.UseHttpsRedirection();  
app.UseStaticFiles();  
app.UseRouting();  
#region Session/Cache Middleware  
    app.UseSession();  
#endregion  
app.UseCors("MyPolicy");  
  
app.MapControllerRoute(  
    name: "default",  
    pattern: "{controller}/{action=Index}/{id?}");  
  
app.MapFallbackToFile("index.html"); ;  
  
app.Run();  





[ApiController]  
    [Route("api/[controller]")]  
    //[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]  
    public class CarRentalController : ControllerBase  
    {  
        private readonly IFranchiseRespository _repository;  
        private readonly IEnquiryRepository _enquiryRepository;  
        private readonly ISearchRepository _searchRepository;  
  
        private readonly ILogger<CarRentalController> _logger;  
  
        public CarRentalController(ILogger<CarRentalController> logger, IFranchiseRespository repository, IEnquiryRepository enquiryRepo, ISearchRepository searchRepo)  
        {  
            _logger = logger;  
            _repository = repository;  
            _enquiryRepository = enquiryRepo;  
            _searchRepository = searchRepo;  
        }  
  
        [EnableCors]  
        [HttpGet("allfranchises")]  
        public async Task<ActionResult<List<FranchiseWebInquiry>>?> GetActiveFranchises()  
        {  
            try  
            {  
                var items = await _repository.SearchFranchisesWebInquiryRes("");  
                if (items != null && items.Count > 0)  
                {  
                    return items;  
                }  
  
                return null;  
  
            }  
            catch (Exception ex)  
            {  
                _logger.LogError(ex.Message);  
                return null;  
            }  
        }  
}  

and this is the client side logic to access this service/api

  let abortController = new AbortController();  
            let apiUrl = https://localhost:7260/api/CarRental/allfranchises;  
            const response = await fetch(apiUrl, {  
                signal: abortController.signal,  
            });  

200893-image.png

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,376 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. mehmood tekfirst 771 Reputation points
    2022-05-11T11:27:35.4+00:00

    Thank you everyone.

    Issue has been fixed.

    I just removed the slash and it worked

    from

     policy.WithOrigins("https://localhost:7260/","https://localhost:44485/")
    

    to

     policy.WithOrigins("https://localhost:7260","https://localhost:44485")
    

    Problem is solved but if anyone can add some good tips then please add .

    0 comments No comments