javascript - ASP .NET Core 使用多个 CORS 策略

标签 javascript c# .net asp.net-core cors

我正在尝试设置 2 个 CORS 策略。一个作为 api 默认值,另一个根据需要在 Controllers 上使用。我想要这样做的原因是因为我有一个端点接收一个包含电子邮件信息的对象并发送一封电子邮件(与我网页上的联系我框一起使用)并且让它只接受来 self 的域的请求。

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

最佳答案

要设置默认 CORS 策略,请使用 app.UseCors(string policyName) 重载。

您的 CORS 请求将失败,因为您拒绝了所有 header 和方法。根据我的阅读,CORS 规范指出,如果任何检查失败,您根本不应设置任何 header 。查看实现 here ,这很可能是您的客户端收到标准 No 'Access-Control-Allow-Origin' header is present 错误的原因,因为根本没有添加 no headers,即使 Origin 检查通过。

以下应该按预期工作,您的 [EnableCors(...)] 装饰器应该覆盖默认值!

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("Example",
            builder => builder.WithOrigins("http://www.example.com")
                                .AllowAnyHeader()
                                .AllowAnyMethod());
        options.AddPolicy("AllowAll",
            builder => builder.AllowAnyOrigin()
                                .AllowAnyHeader()
                                .AllowAnyMethod());
    });

    services.AddMvc();
    //other configure stuff
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors("AllowAll"); //Default

    app.UseMvcWithDefaultRoute();
}

您可能需要将 .AllowCredentials() 添加到您的策略中,但我不确定。阅读here也许?

关于javascript - ASP .NET Core 使用多个 CORS 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43985620/

相关文章:

javascript - 如何使用 Js 文档记录柯里化(Currying)函数

javascript - jQuery:同一事件的多个处理程序

javascript - 如何在 Electron 中获取日期格式 - javascript

javascript - 从 iTextSharp 生成 Base64

c# - 本地启动 Azure 云服务时显示 "Crypto settings changed"消息

.net - 使用命令模式时的依赖注入(inject)

c# - 如何保存已编辑的 pdf?

javascript - "Dynamically bind"变量到另一个

c# - 在 C# 中设置基于过滤器的图形框架

c# - 索引超出范围异常和索引超出数组边界异常有什么区别?