.NET Core 2 Web API:CORS问题 [英] .NET Core 2 Web API: CORS issues

查看:157
本文介绍了.NET Core 2 Web API:CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个前端Angular应用程序,我在其中填写一个小表格,并希望将数据发送到也在本地主机上运行的Web API。我的Angular应用程序在



在这500个服务器错误之后,我看到的是:



解决方案

我认为您需要提及该应用根据博客文章。



准确地说:

  services.AddCors(feature => ; {
feature.AddPolicy(
GlobalCorsPolicy,
builder => builder
.SetIsOriginAllowed((host)=> true)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
);
});

以上所述,这条线确实带来了重大成本。


.SetIsOriginAllowed((host)=> true)


然后,您必须在控制器中显式设置EnableCors( GlobalCorsPolicy))作为装饰属性。
如果要在全球范围内添加内容,则围绕为什么要添加内容进行了讨论和争论,但是我的解决方案实际上是在解决问题。



并且无需添加任何浏览器的Allow-Control-Allow-Origin插件,如果您在代码中添加了这些插件,它将可以正常工作。



经过全部地狱尝试后,我得以通过。



这篇帖子也对我有帮助。我相信,如果您按照这些步骤进行操作,并且只需进行几次迭代就可以自己学习/理解CORS的工作方式以及在.net core中的使用方式,则可以解决此问题。当然,它与.net Web API(fx)中的易用性不同。


So I have a front-end Angular app where I fill in a small form and want to send the data to my Web API which also runs on localhost. My Angular app runs on http://localhost:4200/ and my web api runs on https://localhost:44302/api/input .

On form submit, the following method(s) will be called:

public uploadFormData(): void {
    const form = $('#inputForm')[0];
    const files = ($('#fileUpload') as any);
    const formData = new FormData();
    const file = files[0];

    formData.append('tenant', form[0].value);
    formData.append('title', form[1].value);
    formData.append('file', file, file.name);
    this.uploadService.uploadForm(formData)
      .subscribe(res => this.fileUploaded(res));
  }

  private fileUploaded(data: any): void {
    $('#message').html('Response: 200 OK !');
  }  

This will go to my service, as seen here:

public uploadForm(formdata: any) {
    const url = 'https://localhost:44302/api/input';
    const headers = new Headers({'encrypt': 'multipart/form-data'});
    const options = new RequestOptions({ headers: headers });

    return this.http.post(url, formdata, options)
      .catch(this.errorHandler);
  }

  private errorHandler(error: Response) {
    return Observable.throw(error || 'Some error on server occured: ' + error);
  }  

If I remove the headers & options (and also the options from my http.post), the end result is the same: a 500 server error will be thrown saying

"No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:4200' is therefore not allowed access. 
The response had HTTP status code 500."  

So on my server-side I have a .NET Core 2 Web API running on localhost. Here's my Startcup.cs file so you can see I have configured CORS:

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));

            services.AddMvc();

            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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder =>
                builder.WithOrigins("http://localhost:4200")
                //builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseMvc();
        }  

Here you can find the code for my controller that will accept the input:

// POST api/input
    [HttpPost]
    public IActionResult Post(FormCollection data)
    {
        var inputdata = data;
        //var test = JsonConvert.DeserializeObject<SPInputObject>(data);

        return Ok("POST all good");
    }  

I don't even know if the "FormCollection data" is the correct parameter, because I can't get into my web api due to those CORS issues.

So can anyone see what might be the problem?

EDIT: here you can see what the response/request headers are in Chrome dev tools BEFORE the server 500 error:

Here's what I see AFTER the 500 server error:

解决方案

I think you need to mention the app.UseCors() before app.UseMvc() line code, per this blog post.

To be precise:

services.AddCors(feature => {
                feature.AddPolicy(
                    "GlobalCorsPolicy",
                    builder => builder
                                    .SetIsOriginAllowed((host) => true)
                                    .AllowAnyHeader()
                                    .AllowAnyMethod()
                                    .AllowAnyOrigin()
                                    .AllowCredentials()
                                );
            });

Out of the above, this piece of line really helped at major cost.

.SetIsOriginAllowed((host) => true)

And then, you have to explicitly set the EnableCors("GlobalCorsPolicy")] in your controller as decorative attribute. There are discussions and arguments around why to add if we are adding globally but my solution was practically solving the issue.

And without adding any browser Allow-Control-Allow-Origin plugin, if you add these in the code, it should work.

After total hell lotta attempts, i was able to get it through.

This post also helped me. I am sure this would get resolved if you follow the steps, and with few iterations on your own for your learning/understand how CORS works and to use in .net core. It for sure is different than how easier it was in .net web api (fx).

这篇关于.NET Core 2 Web API:CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆