跨源请求在HTTP POST请求上被阻止

时间:2019-05-25 19:40:06

标签: angular http cors asp.net-core-webapi

我正在从我的角度客户端应用程序向.NET Core Web API发送http请求。尽管启用了CORS,但出现了CORS错误。当我将GET请求发送到SearchController时,一切正常,但是当我将POST请求发送到FormController时,出现了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错误。

1 个答案:

答案 0 :(得分: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();
}