AllowAnyMethod works for some API calls but not for others

拟墨画扇 提交于 2019-12-11 07:45:08

问题


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

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

and

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

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();
}

Why?


回答1:


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

  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.

  2. .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();
    }
    
  3. 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();
    });
});

Then in your configure method you just use the policy name

app.UseCors(DEFAULT_POLICY_NAME);



回答2:


Try using [FromBody]

public void Post([FromBody] Loan loan)

also when you try to send use JSON.stringify instead of modle directly,

this.http.post('http://localhost:1113/api/loans', JSON.stringify(this.model), config).subscribe(data => {
  console.log(data);
});


来源:https://stackoverflow.com/questions/53686395/allowanymethod-works-for-some-api-calls-but-not-for-others

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