简体   繁体   中英

CORS not working with ASP NET 5 Web Api

I'm trying to perform a cross-domain POST request to an ASP.NET 5 Web Api controller action. I always get the following error: "XMLHttpRequest cannot load http://localhost:8082/app/users . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:20724 ' is therefore not allowed access. The response had HTTP status code 500." Curiously only it happens for the POST method. Other methods works fine (GET, PUT) This is my API configuration (Startup.cs):

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

And the controller:

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

My client is angularjs. This is the code:

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

What am I doing wrong??

UPDATE

I already solved the problem. I had an internal error on POST method although browser show me CORS error.

This is what I have in my working Web Api. This is in the App_Start => WebApiConfig.cs file.

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

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