ASP .NET Core使用多个CORS策略 [英] ASP .NET Core use multiple CORS policies

查看:435
本文介绍了ASP .NET Core使用多个CORS策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置2个CORS策略。一个作为api默认值,另一个根据需要在 Controllers 上使用。之所以要这样做,是因为我有一个端点,该端点接收带有电子邮件信息的对象并发送电子邮件(以与网页上的与我联系框使用),并使其仅接受来自我的域的请求。

I am trying to setup 2 CORS policies. One as an api default and the other to use on Controllers as I need them. The reason I want to do this is because I have an endpoint that takes in an object with email info and sends an email (to use with the contact me box on my webpage) and have it only accept requests from my domain.

我的 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发送电子邮件:

Javascript used to send email:

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)重载。

To set a default CORS policy use app.UseCors(string policyName) overload.

您的CORS请求将失败,因为您拒绝所有标头和方法。根据我的阅读,CORS规范指出,如果任何检查失败,则根本不应设置任何标头。请参见实现此处 ,这很可能就是为什么您的客户端将收到标准的不存在 Access-Control-Allow-Origin标头错误,如的原因标头会被添加,即使 Origin 检查通过。

Your CORS requests will be failing because you are rejecting all headers and methods. From what I read, the CORS specification states that you shouldn't set any headers at all if any of the checks fail. See implementation here, this is most likely why your client will be receiving the standard No 'Access-Control-Allow-Origin' header is present error, as no headers are added at all, even though the Origin check passes.

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

The following should work as expected, and your [EnableCors(...)] decorator should override the default!

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()遵守您的政策,但我不确定。在这里阅读?

You may need to add .AllowCredentials() to your policies, but I am not sure. Read here perhaps?

这篇关于ASP .NET Core使用多个CORS策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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