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

泄露秘密 提交于 2020-01-25 09:58:06

问题


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).

回答1:


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.



来源:https://stackoverflow.com/questions/55464574/local-javascript-fetch-post-request-fails-with-call-to-asp-net-core-2-2-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!