【问题标题】:Calling PUT web api : Cross-Origin Request Blocking Issue调用 PUT web api:跨域请求阻塞问题
【发布时间】:2020-02-10 22:51:17
【问题描述】:

我正在尝试从我得到 Cross-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 的角度服务中调用在 ASP.NET 中实现的 PUT web api

我能够毫无问题地从角度调用 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());
        });

【问题讨论】:

    标签: angular asp.net-core asp.net-web-api cors


    【解决方案1】:

    您忘记在每个请求中添加您的策略:

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

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

    [EnableCors("CorsPolicy")]
    

    【讨论】:

    • 我添加了 app.UseCors("CorsPolicy");它有效,实际上我使用的是我在互联网上找到的 app.UseCors(builder => builder.WithOrigins("localhost:4200").AllowAnyHeader())
    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2015-02-08
    • 2015-06-05
    • 2015-06-22
    • 2016-10-23
    • 2019-01-22
    相关资源
    最近更新 更多