3

I'm trying to POST to my ASP.NET Core (RC1) API from jQuery. It works fine when I POST via HttpClient, so I think it's only a stupid thing I'm missing.

I can reproduce my problem on a vanilla default ASP.NET 5 project and this code.

Server

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpPost]
        public IActionResult Post([FromBody]Model input)
        {
            // input is always null

            return Json(input.Value);
        }


        public class Model
        {
            public string Value { get; set; }
        }
    }
}

Client

$.ajax({
    url: "http://localhost:5000/api/values",
    method: "POST",
    contentType: "application/json",
    dataType: "json",
    data: JSON.stringify({
        Value: "some_value"
    })
}).done(function(data) {
    console.log("Done.", data);                         
});  

I played around by removing [FromBody], that returns a model, but the properties were never populated. I also tried the many solutions and workarounds for similar problems on SO, but I think they don't apply to .NET Core or only solve problems usinf [FromBody] and simple types. For example Web Api Parameter always null or using jQuery post to ASP.Net webapi or http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

1 Answer 1

5

I took another few hours until I finally figured it out. As I feared/hoped, it was only one stupid thing:

It took Fiddler to discover that I had minor problems with my CORS configuration. Realizing that I disabled CORS completely in Chrome and it suddenly started to work. The server-side code worked as-is, this is the minimal working client-side code:

$.ajax({
    url: "http://localhost:5000/api/values",
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify({
        value: "some_value"
    })
}).done(function(data) {
    console.log("Done.", data);                         
});  

Please note that contentType is required, without it the modelbinding won't work.

Of course, I had tried this client-side code before, but CORS funked it up: There is an OPTION request for CORS to determine if the request is valid. The browser F12 tools don't make this as obvious as it should be. Interestingly I received the OPTION request in the debugger (and that's why I thought it worked), but I finally discovered via Fiddler that the contentType header was not correctly transmitted in these requests - and that's why the model was not bound correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.