I've been stumped on this one for a few days now. I am a beginner to CORS so navigating this has been very confusing.
What's going wrong: I created a asp.net web api which can successfully send POST requests to my SQL database. I have used POSTMAN to send the data successfully. Once I enable CORS I can no longer send the data. I receive a 400 Bad Request.
Some References of my code:
My Controller which handles the POST request:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ClientsDataAccess;
namespace MS_Clients_Post.Controllers
{
public class ClientsController : ApiController
{
public HttpResponseMessage Post([FromBody] Client client)
{
try
{
using (NewlandiaEntities entities = new NewlandiaEntities())
{
entities.Clients.Add(client);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, client);
message.Headers.Location = new Uri(Request.RequestUri +
client.Id.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
}
My webAPIconfig.cs file (where I enabled CORS):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace MS_Clients_Post
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//enabling cors. The "*","*","*" attributes allow all to access. This should be more limited acccess in the future.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//end of cors code.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
What I'm seeing in Fiddler: OPTIONS Response 200 (Only returned with Angular APP, not POSTMAN
along with POST Response 400 BAD REQUEST (With POSTMAN or Angular APP
TLDR; POST request using ASP.net Web API works before enabling CORS. Why doesn't it work after?
Any help is greatly appreciated!