简体   繁体   中英

Local Javascript Fetch Post Request Fails with call to ASP.NET Core 2.2 Web API. CORS is enabled

I'm trying to make a local post request from a static HTML file to an ASP.NET Core 2.2 Web API. CORS middle-ware is working fine, I can do a simple get request. I ultimately need to make this post request from within a chrome extension. I've been using ASP.NET since the beginning, this is my first attempt at a Core solution, I'm boggled by all the hurdles to overcome, especially this one. Is there something wrong with my Fetch syntax?

Here's my CORS configuration based on this: https://enable-cors.org/server_aspnet.html

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2));
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors(builder => builder.WithOrigins("*"));

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
fetch call in local static html file:
fetch ('http://localhost:49828/Bookmark', {
    method: 'post',
    headers:{'Content-Type': 'application/json'},
    body: JSON.stringify({ ID: 0, Name: 'google', URL: 'google.com', Tags: '' })
})

here's the raw request from Fiddler:
OPTIONS http://localhost:49828/Bookmark HTTP/1.1
Host: localhost:49828
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

console log from chrome:
Access to fetch at 'http://localhost:49828/Bookmark' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

console log from firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49828/Bookmark. (Reason: missing token ‘content-type’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

It's been a while, but I am not sure that .WithOrigins("*") is a valid way to wildcard everything. Have you tried using .AllowAnyOrigin() instead? Even better (from a security standpoint), use WithOrigins with the actual host of where the HTML file is hosted). If that is local, then it would be the localhost address you are serving the HTML page from (which I assume is different than you API).

So something like (where 1234 is the actual local port you are hosting the HTML from).

app.UseCors(builder => builder.WithOrigins("https://localhost:1234"));

If AllowAnyOrigin() works for testing, fine. But don't use it in production. Microsoft considers this an insecure configuration (see https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#set-the-allowed-origins ). Always used named origins in prod.

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