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

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


无法加载http://localhost:52008/Account/GetJWT:预检响应没有 HTTP ok 状态。


我的研究似乎表明 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 查询的结果

http://img2.mukewang.com/61e3c4d900018ef315250663.jpg

慕森卡
浏览 382回答 3
3回答

偶然的你

使用以下代码启用 CORS。.NET Core 版本:2.1 和 Angular 版本:1.6.7public 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");});如果问题仍然存在,请告诉我。

SMILET

您可以在 startup.cs 中配置核心,如下所示,并将源添加到 ConfigurationServices,如下所示。public void ConfigureServices(IServiceCollection services){&nbsp; &nbsp; services.AddCors(options =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; options.AddPolicy("AllowSpecificOrigin",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder => builder.WithOrigins("http://example.com"));&nbsp; &nbsp; });}public void Configure(IApplicationBuilder app, IHostingEnvironment env,&nbsp;&nbsp; &nbsp; ILoggerFactory loggerFactory){&nbsp; &nbsp; loggerFactory.AddConsole();&nbsp; &nbsp; if (env.IsDevelopment())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; app.UseDeveloperExceptionPage();&nbsp; &nbsp; }&nbsp; &nbsp; // Shows UseCors with named policy.&nbsp; &nbsp; app.UseCors("AllowSpecificOrigin");&nbsp; &nbsp; app.Run(async (context) =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; await context.Response.WriteAsync("Hello World!");&nbsp; &nbsp; });}将 CORS 策略添加到特定操作。[HttpGet][EnableCors("AllowSpecificOrigin")]public IEnumerable<string> Get(){&nbsp; &nbsp; return new string[] { "value1", "value2" };}

慕娘9325324

&nbsp; &nbsp; public void ConfigureServices(IServiceCollection services)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//add cors service&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; services.AddCors(options => options.AddPolicy("Cors",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder.AllowAnyOrigin()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .AllowAnyMethod()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .AllowAnyHeader();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } ));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; services.AddMvc(); //&nbsp;//--------------------------------------// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.&nbsp;public void Configure(IApplicationBuilder app, IHostingEnvironment env)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (env.IsDevelopment())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; app.UseDeveloperExceptionPage();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; app.UseCors("Cors");//------>let app use new service&nbsp; &nbsp; &nbsp; &nbsp; app.UseMvc();&nbsp; &nbsp; }在您的控制器内部,确保您从身体上抓取物体//发布请求&nbsp;[HttpPost]&nbsp; &nbsp; public Message Post([FromBody] Message message)&nbsp; &nbsp; {&nbsp; &nbsp; var msg = new Message { Owner = message.Owner, Text = message.Text };&nbsp; &nbsp; db.Messages.AddAsync(msg);&nbsp; &nbsp; db.SaveChangesAsync();&nbsp; &nbsp; return message;}
打开App,查看更多内容
随时随地看视频慕课网APP