c# - EnableCorsAttribute 中缺少方法

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

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

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

但是我在起源上遇到错误:

The best overload for 'EnableCorsAttribute' does not have a parameter named 'origins'

因此,我从元数据访问 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 中。问候

最佳答案

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

在您的场景中并基于 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"));
    });
}

配置方法中:

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

    //code omitted
}

最后在 Controller 中:

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

关于c# - EnableCorsAttribute 中缺少方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51068321/

相关文章:

c# 语法和 Linq,IQueryable

c# - 如何发送 3 次 Ping 请求?

c# - 如何从组合框中的值成员中删除值?

java - 我如何获得 Twilio SID?

asp.net-web-api - 如何加强 ASP.NET WebApi OData 服务以防止滥用?

nginx - 为什么Ingress NGINX删除了我的响应头

c# - 如何使用 FFMPEG 获取视频尺寸

c# - EntityFramework Core Database First 不会以流畅方式生成主键

c# - 如何将原始数据传递给 asp.net core 中间件

c# - 安装了 .Net Core 最新 SDK 但获取 'Framework ' Microsoft.AspNetCore.App',未找到版本 '2.1.0'