在启动中启用CORS失败,并出现预检错误

时间:2018-09-13 19:29:09

标签: c# asp.net asp.net-mvc

我试图在Startup.cs中启用CORS,但没有成功。我在端口4200上有一个Angular应用,试图与我的c#Web应用通信。我一直在Angular中收到此错误

  

无法加载http://localhost:52008/Account/GetJWT:飞行前响应没有HTTP正常状态。

我的研究似乎表明未正确启用CORS。知道我想念什么吗?

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
.......
 app.UseCors("EnableCORS");
 ........
 }

以下是Angular POST请求:

  login(form: NgForm) {
    let credentials = JSON.stringify(form.value);
    console.log(credentials);
    this.http.post("http://localhost:52008/Account/GetJWT", credentials, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    })
  }

POSTMAN查询的结果

enter image description here

4 个答案:

答案 0 :(得分:0)

     public void ConfigureServices(IServiceCollection services)
        {
           //add cors service
            services.AddCors(options => options.AddPolicy("Cors",
                builder => {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                } ));

            services.AddMvc(); // 

// --------------------------------------

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.




 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors("Cors");//------>let app use new service
        app.UseMvc();

    }

在控制器内部,请确保从身体上抓住物体

//后要求

 [HttpPost]
    public Message Post([FromBody] Message message)
    {

    var msg = new Message { Owner = message.Owner, Text = message.Text };
    db.Messages.AddAsync(msg);
    db.SaveChangesAsync();

    return message;

}

答案 1 :(得分:0)

您可以像下面这样在startup.cs中配置核心,然后像下面那样将源添加到ConfigurationServices中。

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.WithOrigins("http://example.com"));
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Shows UseCors with named policy.
    app.UseCors("AllowSpecificOrigin");

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

将CORS政策添加到特定操作中。

[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

参考:Enable Cross-Origin Requests (CORS) in ASP.NET Core

答案 2 :(得分:0)

使用以下代码启用CORS。 .NET Core版本:2.1和angular版本:1.6.7

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .AddJsonOptions(options =>
        {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;                
        });

        services.AddCors();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
    { 
        app.UseCors(options =>
        {
            options.AllowAnyMethod();
            options.AllowAnyOrigin();
            options.AllowAnyHeader();
        });

        app.UseMvc();
    }   
}

角度代码:

$http.post("http://localhost:52008/Account/GetJWT", credentials,{
    headers: new HttpHeaders({
        "Content-Type": "application/json"
})).then(
function(response) {
    console.log(response);
},
function() {
    console.log("unable to login");
});

让我知道问题是否仍然存在。

答案 3 :(得分:0)

更改为您的web.config:

<system.webServer>

    ...

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
</httpProtocol>
</system.webServer>