【问题标题】:Request method POST not allowed in CORS policyCORS 策略中不允许请求方法 POST
【发布时间】:2019-01-04 16:15:21
【问题描述】:

我使用 asp.net core 2.1 构建 web API 并在我的 web 上使用 ajax 来请求 api。

首先我在 GET 方法上遇到问题,我使用 chrome plugin 来解决问题。

但我仍然无法使用 post 方法。

在网页上

POST https://localhost:5001/api/chatbot 400 (Bad Request)

Visual Studio 显示异常。

[40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Hosting.Internal.WebHost1 请求启动 HTTP/1.1 OPTIONS https://localhost:5001/api/chatbot
Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动 HTTP/1.1 选项https://localhost:5001/api/chatbot
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:策略执行失败。 [40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Cors.Infrastructure.CorsService[5] 策略执行失败。 [40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Cors.Infrastructure.CorsService[7] CORS 策略中不允许请求方法 POST。 Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:CORS 策略中不允许请求方法 POST。 [40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Hosting.Internal.WebHost[2] 请求在 21.587 毫秒内完成 204

我已经在 Startup.cs 中使用了 cors - ConfigureServices()

options.AddPolicy("CorsPolicy", policy =>
            {
                policy.AllowAnyOrigin()
                      .AllowAnyHeader()
                      .AllowAnyMethod()
                      .AllowCredentials();
            });

Startup.cs - Configure()

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        string swwwRootPath = env.WebRootPath; 
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseStaticFiles();

        app.UseAuthentication();

        //app.UseHttpsRedirection();
        app.UseExceptionHandler("/Error");
        //app.UseCors(builder => 
        //builder.WithOrigins("file:///").AllowAnyHeader());

        app.UseCors("CorsPolicy");

        app.UseCors(builder => {
            builder.WithOrigins("file:///").AllowAnyHeader();
        });

        app.UseMvc();
    }

还有我的 ajax 函数

var json = {"channel":"web", "message":"", "messagetype":"text", "userid":"xxx", "nodeid":nodeid};
$.ajax({
        method: 'POST',
        url: "https://localhost:5001/api/chatbot",
        data: json,
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        success:...

我的控制器

[ApiController]
[Route("api/[controller]")]
public class ChatbotController : Controller
{
    [HttpPost]
    [EnableCors("CorsPolicy")]
    [Produces("application/json")]
    public ActionResult<string> Post([FromBody]RequestModel request)
    {...

RequestModel

public class RequestModel
{
    public string channel { get; set; }
    public string message { get; set; }
    public string messagetype { get; set; }
    public string userid { get; set; }
    public string nodeid { get; set; }
}

GETPOST 方法都可以在我使用 Postman 时得到正确的响应。

有人知道怎么解决吗?谢谢。

【问题讨论】:

  • 顺便说一句,Access-Control-Allow-* 标头必须由服务器在 response 中发送给 OPTIONS 请求,而不是 request中的客户端> 看来你在这里尝试...

标签: c# .net ajax asp.net-core cors


【解决方案1】:

编辑: 现在您提供了更多代码,这很清楚。 这个

    app.UseCors(builder => {
        builder.WithOrigins("file:///").AllowAnyHeader();
    });

覆盖初始的全局 cors 设置,这就是它不起作用的原因。为函数或控制器启用 cors 听起来不是一个好主意。 CORS 是为了确保浏览器内的安全。你 file:/// 在这里没有意义,也没有必要。

将方法调用app.UseCors();调整为app.UseCors("CorsPolicy");。您必须提供您定义的名称。

【讨论】:

  • 还是同样的错误?你能提供控制器代码吗?您还可以尝试从 Ajax 请求中删除标头吗?它们由服务器在响应中设置,而不是由客户端在请求中设置。
  • Alsami 我使用 [EnableCors("CorsPolicy")],现在可以使用,但仍然有 SerializableError
  • 你能提供你的整个启动代码吗?是否有可能在 app.UseCors(...) 之前执行 app.UseMvc() ?在每个控制器上方编写 enablecors 听起来不是正确的解决方案。
  • 我把 Startup Configure() 放在了
  • 是的。有安全请求 (GET),与 CUD 相关的所有内容都不是安全请求(POST、PUT、DELETE),这是浏览器安全限制。在此处阅读有关 CORS 的更多信息:codecademy.com/articles/what-is-cors
【解决方案2】:

我遇到了类似的问题,我也必须在我的控制器上方添加这行代码,以允许实际调用。请注意,您可以更改标头和方法属性,因为这将允许一切...

[EnableCors(origins: "http://yoursitenamehere.org", headers: "*", methods: "*")]
public class SampleController : ApiController
{}

或者您可以将“http://yoursitenamehere.org”替换为 * 以再次允许所有内容。在发布到 prod 之前不要忘记更改它,哈哈。

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2020-05-13
    • 2019-10-13
    • 2019-06-11
    • 1970-01-01
    • 2018-04-06
    • 2020-11-02
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多