【问题标题】:Missing method in EnableCorsAttributeEnableCorsAttribute 中缺少方法
【发布时间】:2018-12-06 16:14:05
【问题描述】:

我想将 CORS 从我的控制器启用到 asp.net core 2 应用程序中,因此在控制器中添加如下属性:

[EnableCors(origins: "*", headers: "accept,content-type,origin,x-my-header", methods: "*")]

但我在来源上遇到错误:

'EnableCorsAttribute' 的最佳重载没有参数 命名为“起源”

所以我从元数据中访问 EnableCorsAttribute,我发现了这个方法:

namespace Microsoft.AspNetCore.Cors
{

    public class EnableCorsAttribute : Attribute, IEnableCorsAttribute
    {
        public EnableCorsAttribute(string policyName);

        public string PolicyName { get; set; }
    }
}

但是应该是这样的方法吗:

public EnableCorsAttribute(string origins, string headers, string methods);

为什么我没有?我需要安装一些东西吗?我是 Asp.Net Core 的新手,我不明白为什么该方法不在我的 api 中。问候

【问题讨论】:

  • 我能问一下你从哪里得到的印象,它“应该”有三个参数?这是来自某处的一些文档吗?如果是这样,你能链接到它吗?

标签: c# asp.net-web-api asp.net-core


【解决方案1】:

Microsoft.AspNetCore.Cors 包中没有像 EnableCorsAttribute(string origins, string headers, string methods) 这样的属性。

在您的场景中并基于Enable Cross-Origin Requests (CORS) in ASP.NET Core:
如果提供的 cors 配置适用于整个应用程序,则在您的 ConfigureServices 方法中添加 cors 服务:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

然后是Configure方法中的全局cors中间件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(builder => builder
        .WithOrigins("https://my.web.com", "http://localhost:5001")
        .AllowAnyMethod()
        .AllowCredentials()
        .WithHeaders("Accept", "Content-Type", "Origin", "X-My-Header"));

    //code omitted
}

("https://my.web.com", "http://localhost:5001") 替换为您的来源。
如果您想拥有多个 cors 配置,请使用 ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("MyCorsPolicy", builder => builder
            .WithOrigins("https://my.web.com", "http://localhost:5001")
            .AllowAnyMethod()
            .AllowCredentials()
            .WithHeaders("Accept", "Content-Type", "Origin", "X-My-Header"));
    });
}

Configure方法中:

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

    //code omitted
}

最后在控制器中:

[EnableCors("MyCorsPolicy")]
public class MyController : Controller
{ ... }

【讨论】:

  • 我按照你说的尝试,得到Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
  • 如果您发送带有凭据标志的请求,那么您需要设置特定的源域,例如。 WithOrigins("http://localhost:1233").AllowCredentials()。我会更新我的答案以反映这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多