简体   繁体   English

向 ASP.NET Core Web API 发出发布请求时,跨域请求被阻止

[英]Cross-Origin Request Blocked when making post request to ASP.NET Core Web API

I have a Web API that has 2 controllers and I have enabled Cors in my Startup class, here is my ConfigureServices method:我有一个包含 2 个控制器的 Web API,并且我在Startup类中启用了 Cors,这是我的ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.AddAutoMapper();
        }

And here the Configure medhod:这里是配置方法:

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

    app.UseCors(
        options => options.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
    );

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

Now, I have two controllers.现在,我有两个控制器。 When I make a GET request to this method, everything goes ok:当我向此方法发出GET请求时,一切正常:

[Route("api/[controller]")]
[ApiController]
[EnableCors("MyPolicy")]
public class MovieController : ControllerBase
{
    public async Task<IActionResult> Get()
    {
        HttpClient httpClient = new HttpClient();

        var responseMessage = await httpClient.GetAsync("https://copafilmes.azurewebsites.net/api/filmes");

        if (!responseMessage.IsSuccessStatusCode) return null;

        var jsonResult = await responseMessage.Content.ReadAsStringAsync();

        return Ok(jsonResult);
    }

Now, when I try to make a POST to this one:现在,当我尝试对这个发布POST

[Route("api/[controller]")]
[ApiController]
[EnableCors("MyPolicy")]
public class CupController : ControllerBase
{
    private readonly IMapper mapper;

    public CupController(IMapper mapper)
    {
        this.mapper = mapper;
    }

    [HttpPost]
    public IActionResult Post([FromBody] IEnumerable<MovieViewModel> moviesViewModel)
    {
        var movies = mapper.Map<IEnumerable<Movie>>(moviesViewModel).ToList();

        var cup = new Cup(movies);
        cup.Run();

        return Ok(cup.Id);
    }
}

Then I get the message in the browser console:然后我在浏览器控制台中收到消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://worldcupapi-gabs.azurewebsites.net/api/cup. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I am trying to make this post via a Vuejs simple app, you can try it here: https://codesandbox.io/s/j23np20663我正在尝试通过 Vuejs 简单应用程序发布这篇文章,您可以在这里尝试: https ://codesandbox.io/s/j23np20663

Just select 8 cards (click on them and they'll become grey) and click on the "Submit" button.只需选择 8 张卡片(点击它们,它们会变成灰色)并点击“提交”按钮。

Serpent5 provided a valid answer above; Serpent5 在上面提供了有效的答案; I'm adding it as an answer because this is the first hit I got when searching on my CORS issue AND the cause of my issue isn't precisely what Serpent5 indicated, but expanding on his comment provides the answer.我将其添加为答案,因为这是我在搜索我的 CORS 问题时遇到的第一个问题,并且我的问题的原因并不完全是 Serpent5 所指出的,但扩展他的评论提供了答案。

Serpent5's answer basically says another error is preventing the server from responding properly (such as a 500 internal server error), but the browser development tools console shows a CORS error instead. Serpent5 的回答基本上是说另一个错误阻止了服务器正确响应(例如 500 内部服务器错误),但浏览器开发工具控制台显示的是 CORS 错误。

In my case it was because I didn't have https configured correctly on the server.就我而言,这是因为我没有在服务器上正确配置 https。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM