没有& # 39;Access-Control-Allow-Origin& # 39;标头显示在web api中请求的资
本文关键字:api 请求 web Access-Control-Allow-Origin 没有 显示 | 更新日期: 2023-09-27 18:12:27
我正在制作一个从angularJs到web api的post请求。但每次我得到这个错误
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.
我遵循教程
为了解决这个问题,我还安装了Install-Package Microsoft.AspNet.WebApi.Cors
然后我加上
config.EnableCors();
inside WebApiConfig
Register Method.
我还添加了
[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。但是我还是遇到了同样的问题。
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")]
我也遇到过同样的问题,但我用不同的方法解决了这个问题。
如果您遵循本教程的步骤,则:
- 你不需要
Microsoft.AspNet.WebApi.Cors
包 -
将以下内容添加到
Web.config
的配置部分,如下所示<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>