0

I have two projects in .Net Core 6. The first one is.Net Core Web Application and the second one .Net Core Web Api. Now In .Net Core Web API I have a Controller. When I run both project and and enter the url https://localhost:7017/api/WebApi the API gets tiggered and return the data, I also tested the API in post man. Now, I need to access this url of Web API from Web Application. I have written a code for it in jquery

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
    $(document).ready(function(){

        $('#buttonClick').click(function(){           
                $.ajax({
                      type: 'GET',
                      url: 'https://localhost:7017/api/WebApi',
                      contentType: 'application/json',
                      crossDomain: true,
                      headers: {
                      'Access-Control-Allow-Credentials' : true,
                      'Access-Control-Allow-Origin':'*',
                      'Access-Control-Allow-Methods':'GET',
                      'Access-Control-Allow-Headers':'application/json',
                      },
                      success: function(data) {
                        console.log(data);
                      },
                      error: function(error) {
                        alert("FAIL....=================");
                      }
                    });
        }); 
    
    });
</script>

I have also added the cors policiy in program.cs

var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();


builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("https://localhost:7017/");
                      });
});

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // 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.UseCors(MyAllowSpecificOrigins);

app.UseHttpsRedirection();
app.UseWebSockets();


app.UseStaticFiles();


app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();

Now when I Click the button with id '#buttonClick' there is the error in the console

Access to XMLHttpRequest at 'https://localhost:7017/api/WebApi' from origin 'https://localhost:7156' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How Can I solve this issue?

Biraj Dahal
  • 57
  • 1
  • 13
  • 1
    Enable CORS in your application: 1. Install `Install-Package Microsoft.AspNet.WebApi.Cors` 2. Add code in startup: `config.EnableCors();` See more here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api – Sebastian Siemens Feb 09 '22 at 16:12
  • 3
    ^^ and don't put **response** headers in your **request**. – T.J. Crowder Feb 09 '22 at 16:13
  • 1
    This issue is ***extremely*** well-covered here and elsewhere. Please be sure to search thoroughly before posting. – T.J. Crowder Feb 09 '22 at 16:14
  • config.EnableCors() isn't going to work for Core 6. You have to enable it in the middleware: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0 – GH DevOps Feb 09 '22 at 16:15
  • Quote the docs: *The call to UseCors must be placed after UseRouting, but before UseAuthorization.*. To also reiterate TJC; remove those `headers` from your ajax call. `Access-*` headers are what the server sends to the browser, not what the browser sends to the server – Caius Jard Feb 09 '22 at 16:17

0 Answers0