【问题标题】:Angular CORS , C# server side failingAngular CORS,C# 服务器端失败
【发布时间】:2019-06-26 02:27:50
【问题描述】:

我正在使用对 C# WEB API 进行 http post 调用并导致“No Access-Control-Allow-Origin”错误

这个方法被运行时调用。使用此方法向容器添加服务。

WEB API - StartUp.cs

    public void ConfigureServices(IServiceCollection services)
    {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",builder => 
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials() );
              });

        services.AddMvc().AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new ReadOnlyJsonContractResolver();
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, WhiteBoxDBContext context)
    {
        app.UseCors("CorsPolicy");
        app.UseMvc();
    }

//控制器

     [HttpPost]
     [Route("ValidateUser")]
     [EnableCors("CorsPolicy")]
     public ValidateUser<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

错误:-

不确定我遗漏了什么,但这应该可行....

【问题讨论】:

  • 您是否尝试在所有控制器上启用 cors 而不是这个特定操作?哦,这可能不是我认为的确切错误,在某些情况下,您有此错误,但它不是 cors 错误,是服务器错误未捕获或其他错误。尝试调试我认为的 api 代码或您的回报。检查网络开发工具,看看你的请求是否有错误
  • @Paul - 现在会尝试...
  • 你如何处理异常?你有任何异常处理过滤器或中间件吗?

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


【解决方案1】:

1) 安装包 Microsoft.AspNet.WebApi.Cors

Install-Package Microsoft.AspNet.WebApi.Cors

2) 打开 webapiconfig。 cs 文件并在 Register() 方法中添加以下行(在添加路由之前):

config.EnableCors();

3) 使用以下行装饰您的控制器/操作方法(如果适用):

 [EnableCors(origins: "http://www.myclientsite.com", headers: "*", methods: "*")]
public class TestController : ApiController{   .......   }

【讨论】:

【解决方案2】:
services.AddCors();
            services.AddCors(o => o.AddPolicy("AllowOrigin", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

// 配置

public void Configure(IApplicationBuilder app, IHostingEnvironment env, WhiteBoxDBContext context)
    {
        app.UseCors("AllowOrigin");
        app.UseMvc();
    }

//控制器

[HttpPost]
     [Route("ValidateUser")]
     public ValidateUser<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

【讨论】:

  • 确保你的 chrome CORS 扩展应该关闭
猜你喜欢
  • 2019-05-16
  • 1970-01-01
  • 2015-03-20
  • 2020-06-14
  • 2020-06-16
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多