首页 文章

发送POST请求时,Angular2与ASP.NET Core CORS发生问题

提问于
浏览
4

通过我的Angular 2服务向ASP.NET Core API发送POST请求时出现问题 . 我目前收到HTTP 500错误:

“XMLHttpRequest无法加载http://localhost:51014/api/sites . 请求的资源上没有'Access-Control-Allow-Origin'标头 . 因此,不允许来源'http://localhost:3000' . 响应的HTTP状态代码为500.”

我没有在GET请求上收到此错误,据我所知,我在服务器端正确设置了CORS?

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddCors();
        services.AddMvc();            

        ....
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...

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

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

    }

SitesContoller.cs

// POST: api/Sites
    [HttpPost]
    public async Task<IActionResult> PostSite([FromBody] Site site)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Sites.Add(site);
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (SiteExists(site.Id))
            {
                return new StatusCodeResult(StatusCodes.Status409Conflict);
            }
            else
            {
                throw;
            }
        }

        return CreatedAtAction("GetSite", new { id = site.Id }, site);
    }

我的Angular 2服务:

site.service.ts snippet

public createSite(site: Site): Observable<Site> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(site);

    return this.http
        .post(this.apiUrl + 'sites', { body }, options)
        .map((res: Response) => res.json());
}

1 回答

  • 0

    您需要将EnableCors属性添加到SiteController类 . 像这样

    [EnableCors(origins: "http://<SOME_SITE>", headers: "*", methods: "*")]
    public class SiteController {
    .....
    }
    

    参考这个link

    无法告诉你代码片段是这样的,你确实需要它 .

相关问题