skip to Main Content

I’m building a C# application for which i have to update in database and that needs to make requests to an API running on a different domain. However, when I try to make these requests, I’m getting CORS errors.

I’ve read about CORS and understand that it’s a security feature that browsers use to prevent cross-domain requests, but I’m not sure how to enable it in my C# application.

Can someone please explain how to enable CORS in a C# application and provide an example of how to make a cross-domain request using CORS? Thanks in advance!

I had tried to install "Microsoft.AspNetCore.Cors" from package manager but is not working.

3

Answers


  1. Copy And Paste In Program.cs

    builder.Services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.WithOrigins("*")
               .AllowAnyMethod()
               .AllowAnyHeader();
    
    // U Can Filter Here
    }));
    

    Then write this, also in Program.cs. But write it in the correct order, after app.UseRouting(); and before app.UseAuthentication();https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-7.0#middleware-order

    app.UseCors("MyPolicy");
    
    Login or Signup to reply.
  2. using (var client = new HttpClient())

    Login or Signup to reply.
  3. In C# MVC application we can add Microsoft.AspNet.WebApi.Cors NuGet package. After successfully installing this package use the below line in a controller,

    using System.Web.Http.Cors;
    

    And, EnableCORS before defining APIs like:

    [HttpPost]
    [EnableCors(origins: "*", methods: "*", headers: "*")]
    public int GetId(int id)
    {
         return id;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search