ASP .NET Core使用多个CORS策略

时间:2017-05-15 17:37:17

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

我正在尝试设置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 个答案:

答案 0 :(得分:5)

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

您的CORS请求将失败,因为您拒绝所有标头和方法。根据我的阅读,CORS规范声明如果任何检查失败,您根本不应设置任何标头。请参阅实施here,这很可能是因为您的客户端会收到标准No 'Access-Control-Allow-Origin' header is present错误,因为没有标题会被添加,即使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

答案 1 :(得分:2)

配置方法

app.UseRouting();
app.UseCors("CorsApi");
app.UseAuthentication();

ConfigureServices方法

services.AddCors(options =>
    {
        options.AddPolicy("CorsApi",
            builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
        .AllowAnyHeader()
        .AllowAnyMethod());
    });