After enabling CORs on a Web API, I encountered an issue where GET and POST requests were failing on Chrome. Interestingly, the GET request worked fine on MS Edge, but the POST request threw two error messages in the console:
The request could not be processed by the server due to invalid syntax.
XMLHttpRequest: Network Error 0x80070005, Access is denied.
The POST code consists of a standard Ajax request with cross-domain enabled:
$.ajax({
type: "POST",
crossDomain: true,
url: 'http://localhost:50915/api/addjob',
data: JSON.stringify(Job),
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr) {
alert("The result is : " + status + ": " + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
On the Web API side, I have installed the CORs Nuget package and made the necessary configurations to enable it:
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var JsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
if (JsonFormatter != null)
JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
And the Controller:
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/addjob")]
[EnableCors(origins: "http://localhost", headers: "*", methods: "*")]
public void AddJob([FromBody] Job job)
{
using (_tmsPortalDb)
{
_tmsPortalDb.Jobs.Add(job);
_tmsPortalDb.SaveChanges();
}
}
Both URLs are localhost but on different ports, and they are part of the same VS Solution as separate projects. I believed that enabling CORs for localhost debugging should resolve the issue. Is there something that I might have overlooked?