CORS不适用于ASP.NET 5 Web Api

本文关键字:Web Api NET ASP 不适用 适用于 CORS | 更新日期: 2023-09-27 18:35:47

我正在尝试对ASP.NET 5 Web Api控制器操作执行跨域POST请求。我总是收到以下错误:"XMLHttpRequest无法加载http://localhost:8082/app/users.请求的资源上不存在"Access Control Allow Origin"标头。原点'http://localhost:20724因此不允许访问。响应的HTTP状态代码为500。"奇怪的是,只有POST方法才会发生这种情况。其他方法运行良好(GET、PUT(这是我的API配置(Startup.cs(:

public void ConfigureServices(IServiceCollection services)
{
 services.AddCors(options =>
            {
                // Define one or more CORS policies
                options.AddPolicy("AllowAll", builder => 
                    builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            });
}

控制器:

[EnableCors("AllowAll")]
[Route("app/[controller]")]
public class UsersController : Controller
// POST api/users
[HttpPost]
public IActionResult Post([FromBody]UserEntity user)
{           
    if (!ModelState.IsValid) //Valida el modelo recibido 'user'
        return new HttpStatusCodeResult(422); 
    else
    {
        UserEntity userCreated = _userServices.CreateUser(user);
        if(userCreated != null)
            return CreatedAtRoute("GetUserById", new { controller = "Users", id = userCreated.Id }, userCreated);
        else
            return new HttpStatusCodeResult(500);
    }
}

我的客户是angularjs。这是代码:

$http.post(Config.apiHost + "users", user);

我做错了什么??

更新

我已经解决了这个问题。我在POST方法上有一个内部错误,尽管浏览器显示了CORS错误。

CORS不适用于ASP.NET 5 Web Api

这是我工作的WebApi中的内容。这在App_Start=>WebApiConfig.cs文件中。

    public static void Register(HttpConfiguration config)
    {
       //this enables it by calling the that method defined below.
        EnableCrossSiteRequests(config);
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(
            origins: "*",
            headers: "*",
            methods: "*");
        config.EnableCors(cors);
    }