【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource in web apiWeb api 中请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2015-09-13 07:39:14
【问题描述】:

我正在从 angularJs 向 web api 发出发布请求。但每次我收到这个错误

XMLHttpRequest cannot load http://localhost:45525/api/account/register. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:45725' is therefore not allowed access. The response had HTTP status code 500.

我正在关注这个tutorial

为了解决这个问题,我也安装了

Install-Package Microsoft.AspNet.WebApi.Cors

然后我添加了

config.EnableCors();

WebApiConfig注册方法里面。

我也加了

    [RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        private AuthRepository _repo = null;

        public AccountController()
        {
            _repo = new AuthRepository();
        }

        // POST api/Account/Register
        [EnableCors("*", "*", "PUT, POST")]
        [AllowAnonymous]
        [Route("Register")]
        [HttpPost]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await _repo.RegisterUser(userModel);

            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _repo.Dispose();
            }

            base.Dispose(disposing);
        }
}

在帐户控制器。但我仍然遇到同样的问题。

角码

var _saveRegistration = function (registration) {
  var serviceBase = 'http://localhost:45525/';
  _logOut();

  return $http.post(serviceBase + 'api/account/register', registration)
     .then(function (response) {
            return response;
     }); 
};

【问题讨论】:

  • 您确定执行的是 POST 而不是 GET?
  • 从你所说的你所做的,那么应该启用 CORS。你能显示代码AcccountController
  • 试试[EnableCors("*", "*", "PUT,POST")],就是去掉方法之间的空格。
  • @RichardSchneider:非常感谢。这行得通。 :)

标签: c# asp.net angularjs asp.net-web-api


【解决方案1】:

去除 CORS 属性中 web 方法之间的空格

[EnableCors("*", "*", "PUT,POST")]

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,但我用不同的方式解决了这个问题。

    如果您按照教程步骤进行操作,那么:

    1. 你不需要Microsoft.AspNet.WebApi.Cors
    2. 将以下内容添加到Web.config中的配置部分作为here

      <system.webServer>
        <handlers>
          <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
          <remove name="OPTIONSVerbHandler" />
          <remove name="TRACEVerbHandler" />
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
      </system.webServer>
      

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2014-07-28
      • 2014-01-19
      相关资源
      最近更新 更多