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