我正在尝试设置2个CORS策略。一个作为API默认值,另一个在我需要时在Controllers
上使用。我想这样做的原因是因为我有一个端点,它接收一个带有电子邮件信息的对象并发送一封电子邮件(与我网页上的“联系我”框一起使用),并让它只接受来自我的域的请求。
我的startup.cs
文件片段:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("Example",
builder => builder.WithOrigins("http://www.example.com"));
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin());
});
services.AddMvc();
//other configure stuff
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(builder =>
{
builder.AllowAnyHeader();
builder.AllowAnyMethod();
builder.WithOrigins("AllowAll");
});
app.UseMvcWithDefaultRoute();
}
我的emailcontroller.cs
文件:
using System.Threading.Tasks;
using MyAPI.Models;
using MyAPI.Services;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace MyAPI.Controllers
{
[Produces("application/json")]
[Route("api/Email")]
[EnableCors("Example")]
public class EmailController : Controller
{
private readonly IEmailSender _emailSender;
public EmailController(IEmailSender emailSender)
{
_emailSender = emailSender;
}
[HttpPost]
public async Task Post([FromBody] Email email)
{
await _emailSender.SendEmailAsync(email);
}
}
}
用于发送电子邮件的JavaScript:
function sendEmail(email)
{
var urlToApi = "http://<ipToApi>:5000/api";
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(email),
url: urlToApi + "/email/",
success: function(data) {
console.log(data);
console.log('probably sent');
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
alert("There was like, an error doing that");
}
});
}
这是我尝试从http://www.example.com发送的结果
XMLHttpRequest cannot load http://<ipToApi>:5000/api/email/.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://www.example.com' is therefore not allowed access.
编辑
这一方法:
services.AddCors(options =>
{
options.AddPolicy("Example",
builder => builder.WithOrigins("http://www.example.com")
.AllowAnyHeader()
.AllowAnyMethod());
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
2条答案
按热度按时间bvuwiixz1#
要设置默认CORS策略,请使用
app.UseCors(string policyName)
重载。您的CORS请求将失败,因为您拒绝了所有的头和方法。据我所知,CORS规范规定,如果任何检查失败,您都不应该设置任何头。请参阅这里的实现,这很可能是为什么您的客户端将收到标准的
No 'Access-Control-Allow-Origin' header is present
错误,因为即使Origin
检查通过,也根本没有添加 no 头。下面的代码应该可以正常工作,并且您的
[EnableCors(...)]
装饰器应该覆盖默认值!您可能需要将
.AllowCredentials()
添加到您的策略中,但我不确定。here可能是什么意思ozxc1zmp2#
Configure方法
ConfigureServices方法