AllowAnyMethod适用于某些API调用,但不适用于其他API调用 [英] AllowAnyMethod works for some API calls but not for others

查看:247
本文介绍了AllowAnyMethod适用于某些API调用,但不适用于其他API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此问题中提到的表格,但是何时我提交我得到

I have the form mentioned in this question, but when I submit it I get

跨域请求被阻止:同源策略禁止读取 http://localhost:1113上的远程资源/api/loans . (原因:CORS标头"Access-Control-Allow-Origin"缺失).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:1113/api/loans. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

跨域请求被阻止:同源策略禁止读取 http://localhost:1113上的远程资源/api/loans . (原因:CORS请求未成功).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:1113/api/loans. (Reason: CORS request did not succeed).

我之前通过将其添加到Startup中的API Configure中来解决了另一个API调用:

I had fixed this for another API call previously by adding this to me API's Configure in Startup:

app.UseCors(options => options.WithOrigins("*").AllowAnyMethod());

但是现在由于某种原因,它阻止了操作所在的呼叫

But now for some reason it is blocking the call where the action is

// POST api/loans
[HttpPost]
public void Post(Loan loan)
{
    _context.Loans.Add(loan);
    _context.SaveChanges();
}

为什么?

推荐答案

这是一个模糊的问题,因此我将给出一些提示.

This is a vague question so I'll give a few tips on what it could be.

  1. 首先通过打开所有异常开始 有可能在cors发生之前获得例外,因此您可以申请 在添加cors标头之前返回了错误响应.

  1. First start off by Turning on all Exceptions There's a chance you're getting an exception before the cors happens so you application is returning an error response before it can add the cors headers.

.Net-Core require属性用于解决如何对数据进行模型绑定.因此,您的http post方法应该需要[FromForm]或[FromBody]属性

.Net-Core require attribute for resolving how to model bind the data. So you're http post method should require either [FromForm] or [FromBody] attributes

[HttpPost]
public void Post([FromForm] Loan loan)
{
    _context.Loans.Add(loan);
    _context.SaveChanges();
}

  • 确保您实际上正在使用自己的cors政策.除非您使用的是.Net Core的旧版本,否则您应该通过Configure Services方法而不是configure方法来实现cors策略

  • Make sure you are actually using you're cors policy. Unless your using an old version of .Net Core you should be implementing your cors policy from the Configure Services method and not the configure method

    尝试像这样实施您的政策:

    Try implementing your policy like so:

    services.AddCors(options =>
    {
        options.AddPolicy(DEFAULT_POLICY_NAME, policy =>
        {
            policy.SetIsOriginAllowedToAllowWildcardSubdomains() 
                 .AllowAnyOrigin()
                 .AllowAnyHeader()
                 .AllowAnyMethod()
                 .AllowCredentials();
        });
    });
    

    然后在您的configure方法中,您只需使用策略名称

    Then in your configure method you just use the policy name

    app.UseCors(DEFAULT_POLICY_NAME);
    

    这篇关于AllowAnyMethod适用于某些API调用,但不适用于其他API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆