首页 > 解决方案 > 调用 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());
        });

标签: angularasp.net-coreasp.net-web-apicors

解决方案


您忘记将您的策略​​添加到每个请求中:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("CorsPolicy");

    // ...
}

如果您只想将策略添加到所需的控制器和操作,那么您不需要编写上述代码,但是应用此属性操作或控制器:

[EnableCors("CorsPolicy")]

推荐阅读