1

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.

3

1 Answer 1

1

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry I need configuration for ASP NET 5 Web Api (new). My configuration must be in Startup.cs class

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.