【发布时间】: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