简体   繁体   English

调用 ASP.NET Core 2.2 Web API 时本地 Javascript 提取发布请求失败。 CORS 已启用

[英]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.我正在尝试从静态 HTML 文件向 ASP.NET Core 2.2 Web API 发出本地发布请求。 CORS middle-ware is working fine, I can do a simple get request. CORS 中间件工作正常,我可以做一个简单的获取请求。 I ultimately need to make this post request from within a chrome extension.我最终需要从 chrome 扩展程序中发出这个帖子请求。 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.我从一开始就一直在使用 ASP.NET,这是我第一次尝试 Core 解决方案,我被所有要克服的障碍所困扰,尤其是这个障碍。 Is there something wrong with my Fetch syntax?我的 Fetch 语法有问题吗?

Here's my CORS configuration based on this: https://enable-cors.org/server_aspnet.html这是我基于此的 CORS 配置: 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.已经有一段时间了,但我不确定 .WithOrigins("*") 是通配所有内容的有效方法。 Have you tried using .AllowAnyOrigin() instead?您是否尝试过使用 .AllowAnyOrigin() 代替? Even better (from a security standpoint), use WithOrigins with the actual host of where the HTML file is hosted).更好的是(从安全角度来看),将 WithOrigins 与托管 HTML 文件的实际主机一起使用)。 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).如果它是本地的,那么它将是您为 HTML 页面提供服务的本地主机地址(我认为它与您的 API 不同)。

So something like (where 1234 is the actual local port you are hosting the HTML from).所以类似于(其中 1234 是您托管 HTML 的实际本地端口)。

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

If AllowAnyOrigin() works for testing, fine.如果 AllowAnyOrigin() 用于测试,那很好。 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 ). Microsoft 认为这是一种不安全的配置(请参阅https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#set-the-allowed-origins )。 Always used named origins in prod.始终在 prod 中使用命名来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 向 ASP.NET Core Web API 发出发布请求时,跨域请求被阻止 - Cross-Origin Request Blocked when making post request to ASP.NET Core Web API 如何使用提取将JavaScript中的FormData发送到ASP.NET Core 2.1 Web API - How to send FormData from javascript to ASP.NET Core 2.1 web API using fetch Api 中的 Post 请求错误 Fetch with asp.net C # - Post request error in Api Fetch with asp.net C # Ajax POST 调用被 ASP NET Web API 的 CORS 阻止 - 对预检请求的响应未通过访问控制检查 - Ajax POST call blocked by CORS from ASP NET Web API - Response to preflight request doesn't pass access control check Asp.NET Web API和SignalR Cors - Asp.NET Web API and SignalR Cors 未处理 Web API 请求 Asp.net Core 3.1 和 Axios - Web API Request not processed Asp.net Core 3.1 and Axios 无法使用JavaScript将HTTP POST请求发送到ASP.NET Web API Controller - Unable to send a http POST request to ASP.NET web api Controller using javascript Asp .Net Core 2.2 Razor页面Ajax呼叫发布不起作用 - Asp .Net Core 2.2 Razor Pages Ajax Call Post not working Firefox 上的 ASP.NET Core Web API CORS 错误,但在 Chrome 上没问题 - ASP.NET Core Web API CORS error on Firefox but okay on Chrome 带有POST请求的asp.net Web API角度CORS预检问题 - asp.net web api angular CORS preflight issue with POST requests
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM