angular - 调用 PUT web api:跨域请求阻塞问题
问题描述
我正在尝试从我得到的角度服务调用在 ASP.NET 中实现的 PUT web apiCross-Origin Request Blocking: The "Same Origin" policy does not allow access to the remote resource located at http://localhost:8888/api/users/17. Reason: Missing method in the "Access-Control-Allow-Methods" header
我能够毫无问题地从角度调用 GET 和 POST 方法
源代码 :
edit(user : User) : Observable<object> {
his.httpClient.put('http://localhost:8888/api/users/' + user.userId, user);
}
这是 PUT web api:
[HttpPut("{id}")]
public async Task<ActionResult> Put(int id, [FromBody] UserViewModel model)
{
try
{
var user = _mapper.Map<UserViewModel, User>(model);
var status = await _repository.UpdateUserAsync(user);
if (!status)
{
return BadRequest("failed to edit user");
}
return Ok(_mapper.Map<User, UserViewModel>(user));
}
catch (Exception exp)
{
_loger.LogError(exp.Message);
return BadRequest("failed to edit user");
}
}
我还在启动类的服务中添加了 Cors,如下所示:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
解决方案
您忘记将您的策略添加到每个请求中:
public void Configure(IApplicationBuilder app)
{
app.UseCors("CorsPolicy");
// ...
}
如果您只想将策略添加到所需的控制器和操作,那么您不需要编写上述代码,但是应用此属性操作或控制器:
[EnableCors("CorsPolicy")]
推荐阅读
- .htaccess - 通过 htaccess 将 index.html 和所有 http、https、www 和非 www 版本的主页 URL 重定向到 https://www 根 url 的 301 重定向
- python - 如何解决 Abaqus Python 脚本中的 OdbError?
- ios - 如何编辑 alertViewController 而不根据操作将其关闭
- visual-studio - Crystal Reports - 在数据库字段下的表格中添加字段
- vue.js - 如何在 vuex 发布请求中从状态传递值
- mysql - 需要在 MySQL 中使用 ALTER COLUMN 将列类型更改为 NOT NULL AUTO_INCREAMENT
- abap - 使用 COND 运算符将非空行附加到 itab
- mysql - 将行显示为列
- android - 在 Kotlin 中检查两个对象的某些(不是全部)属性是否相等的惯用方法
- c - fseek 和 Microsoft 的 CRT UNICODE 支持存在问题