简体   繁体   中英

How to allow CORS in ASP.NET WebAPI

I'm trying to do an ajax post request from my web app to my ASP.NET endpoint (everything locally) to insert data in my database but I'm always getting POST http://localhost:44326/radar/insertConfig.net::ERR_CONNECTION_RESET .

What I've gattered so far: The endpoint works perfectly when called via Insomnia; I have other GET requests working perfectly in the same conditions (same page, same domains, etc); I have tested my POST request to a public endpoint and everything worked fine; The request never leaves the browser (or never reaches the destination). The issue only happens when sending a POST request to my API from my web application.

What I've tried: using another browser (Chrome, Edge, Firefox), deleting cookies, clearing cache, reseting my connections, reseting my computer, trying from a different connection.

Note1: I'm using a VPN and an antivirus that I cannot turn off (neither).

Note2: When done via firefox the error becomes: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:44326/radar/insertConfig. (Reason: CORS request did not succeed). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:44326/radar/insertConfig. (Reason: CORS request did not succeed).

My request:

var json = JSON.stringify(obj);
var url = "http://localhost:44326/radar/insertConfig";
$.post(url, json, function (status) {
    if (status == "success")
        alert("yay");
    else
        alert("nay");
}, "json");

The line at which the error happens: plugins.bundle.js:9838

xhr.send( options.hasContent && options.data || null );

What could be the possible problem?

Update: I added a middleware in my server that looks like this:

app.Use(async (context, next) =>
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            await next.Invoke();
        });

But if I do that, then the return becomes 415 (unsupported media type). I tried to fix that by changing my request:

$.ajax({
    url: url,
    type: 'post',
    data: json,
    contentType: 'application/json',
    dataType: 'json',
    success: function (status) {
        if (status == "success")
            alert("yay");
        else
            alert("nay");
    }
});

But then again, the CORS error returns...

from the error message it looks like your client and your server are from different domains, in order to be able to call your server from a different domain you need to enable CORS on your server.

for a asp.net server you can use Microsoft.AspNet.WebApi.Cors nuget package and add EnableCors attribute on your controller as follow [EnableCors(origins: "http://{your-client-domain}", headers: "*", methods: "*")]

I had to change some stuff for this to work, here was my solution:

step 1: add this to the ConfigureServices and Configure (by default they're in the Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
        services.AddCors(options =>
        {
            options.AddPolicy(name: "MyPolicy",
                builder =>
                {
                    //This is how you tell your app to allow cors
                    builder.WithOrigins("*")
                            .WithMethods("POST", "DELETE", "GET")
                            .AllowAnyHeader();
                });
        });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors("MyPolicy");
}

step 2: Change the request to $.ajax instead of $.post

$.ajax({
    url: url,
    type: "post",
    crossDomain: true,
    data: json,
    contentType: "application/json",
    dataType: "json"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM