Cross Origin Request Blocked on HTTP POST request

2019-08-17 08:07发布

I'm sending http requests from my angular client app to .NET core web API. I'm getting a CORS error although I enabled CORS. When I send a GET request to my SearchController that goes through just fine, but when I send a POST request to my FormController I get the CORS error.

I've tried running it in chrome, same result.

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


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

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

As you can see I have it configured to allow any origin

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);

    }
}

The POST request that's not working

    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);
        }
    }

The FormController class

Like I said earlier it works for GET requests to my SearchController. But for some reason I get the CORS error on the POST request to my FormController.

1条回答
Fickle 薄情
2楼-- · 2019-08-17 08:28

Enabling 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();
}
查看更多
登录 后发表回答