I'm having an issue where I can't get POST content to work as expected in Web API.
Following the tutorials I should be able to have routes in a controller that look like the following (form 1):
[Route("my-post-method")]
public HttpResponseMessage MyPostMethod(MyModel model)
{
Request.CreateResponse(HttpStatus.OK, model.SomeNumber * 5);
}
But this doesn't work. Instead I have to do the following (form 2):
[Route("my-post-method")]
public HttpResponseMessage MyPostMethod()
{
var text = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var model = JsonConvert.DeserializeObject<MyModel>(text);
Request.CreateResponse(HttpStatusCode.OK, model.SomeNumber * 5);
}
Now, I think this has something to do with the CORS setup on the project but I'm not sure. If I try to make the request to form 1 via Postman everything works as intended. If I try to make the request to form 1 via the browser and I don't set the Content-Type header I get an unsupported media type error on the POST request (this is what I expect to happen), but if I set the Content-Type header to "application/json" then the Web API returns a 404 response on the OPTIONS preflight request. Additionally adding a [FromBody] attribute to the method argument doesn't do anything.
The Web.config contains:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
and the startup config class has:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
jsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.EnsureInitialized();
}