简体   繁体   中英

No 'Access-Control-Allow-Origin' header is present on the requested resource in web api

I am making a post request from angularJs to web api. but every time I'm getting this error

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.

I'm following this tutorial

to solve this problem, I have also installed

Install-Package Microsoft.AspNet.WebApi.Cors

Then I added

config.EnableCors();

inside WebApiConfig Register Method.

and also I added

    [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);
        }
}

at account controller. But still I'm getting same problem.

AngularCode

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

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

删除CORS属性中Web方法之间的空格

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

I had the same problem, but I have solved the problem in a different way.

If you followed the tutorial steps then:

  1. you don't need Microsoft.AspNet.WebApi.Cors package
  2. Add the following to the configuration section in Web.config as 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM