【问题标题】:Cross Origin Request Blocked on HTTP POST requestHTTP POST 请求被阻止的跨域请求
【发布时间】:2019-10-11 23:17:51
【问题描述】:

我正在从我的 Angular 客户端应用程序向 .NET 核心 Web API 发送 http 请求。虽然我启用了 CORS,但我收到了 CORS 错误。当我向我的 SearchController 发送一个 GET 请求时,它通过就好了,但是当我向我的 FormController 发送一个 POST 请求时,我得到了 CORS 错误。

我尝试在 chrome 中运行它,结果相同。

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }


            app.UseCors(builder =>
                builder.AllowAnyOrigin()
                );

            app.UseHttpsRedirection();
            app.UseMvc();
 }

如您所见,我已将其配置为允许任何来源

const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token',

    })
};



@Injectable()

export class SendFormService
{
    submitUrl : string = "https://localhost:5001/api/submitForm";

    constructor(private http : HttpClient){ }

    public SendFormData(formData : RoadmapForm) : Observable<RoadmapForm>
    {
        //remember to error handle
        return this.http.post<RoadmapForm>(this.submitUrl, formData, httpOptions);

    }
}

不工作的 POST 请求

    public class Form
    {
        string title;
        string summary;
        string body;
        string[] tags;

    }

    [Route("api/submitForm")]
    [ApiController]

    public class FormController : ControllerBase
    {
        [HttpPost]
        public void Post([FromBody] Form formData)
        {
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;

            Console.WriteLine(formData);
        }
    }

FormController 类

就像我之前说的,它适用于对我的 SearchController 的 GET 请求。但由于某种原因,我在对 FormController 的 POST 请求中收到了 CORS 错误。

【问题讨论】:

  • POST请求响应的HTTP状态码是什么?使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?

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


【解决方案1】:

启用 CORS

public void ConfigureServices(IServiceCollection services)
{
      services.AddCors();
      services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(
        options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
    );

    app.UseMvc();
}

【讨论】:

  • 哇,非常感谢。原来在 AddMvc() 不知道顺序重要之后我有 AddCors()。
猜你喜欢
  • 2017-02-06
  • 2019-02-22
  • 2018-09-09
  • 1970-01-01
  • 2019-11-04
  • 2023-03-03
  • 2015-06-22
  • 2021-06-26
相关资源
最近更新 更多