通过我的Angular 2服务向ASP.NET Core API发送POST请求时出现问题。我目前收到HTTP 500错误:
" XMLHttpRequest无法加载http://localhost:51014/api/sites。 No' 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);
}
My Angular 2服务:
site.service.ts片段
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());
}
答案 0 :(得分:0)
您需要将EnableCors属性添加到SiteController类。喜欢这个
[EnableCors(origins: "http://<SOME_SITE>", headers: "*", methods: "*")]
public class SiteController {
.....
}
请参阅此link
无法告诉你代码片段是这种情况,你确实需要它。