MyDaftQuestions
MyDaftQuestions

Reputation: 4701

Cannot post to another domain using ajax despite having CORS enabled

I'm using MVC.net and sending post data to my Web API 2 controller. I keep getting a 500 internal server error message.

I am trying to post to another domain if that matters? I have 2 visual studio instances running, one acting as the client, the other as the server. I have enabled CORS.

The GET works fine with this set up, but now I'm trying to post.

My controller on the 'server' is

[HttpPost]
[Route("api/cms/")]
public IHttpActionResult Post([FromBody]int accountId, [FromBody]string content, [FromBody]string paneId, [FromBody]string url)
{
    //content
}

The javascript on the 'client' I'm using is

function ajaxStart(type, url, data, successDelegate, failDelegate, errorDelegate) {
    $.ajax({
        type: type.toUpperCase(),
        url: url,
        contentType: "application/json;charset=utf-8",
        data: data,
        dataType: "json",
        success: function (response) {
            successDelegate(response);
        },
        failure: function (e) {
            failDelegate(e.statusText);
        },
        error: function (e) {
            errorDelegate(e.statusText);  //always hit
        }
    })
}

The data is created with (I've purposely used nonsense strings just to ensure there is nothing wrong with the formatting)

var data = JSON.stringify({ accountId: 1, paneId: "_selectedPaneNumber", url: "_url", content: "content" });

And the 'header' view in Google Chrome Dev Tools shows:

enter image description here

I have no idea what I've done wrong.

Upvotes: 2

Views: 128

Answers (2)

Nkosi
Nkosi

Reputation: 247591

The javascript on the client side appears fine. The problem seems to be with the ApiController's action and parameter binding.

At most one parameter is allowed to read from the message body. So this will not work:

public IHttpActionResult Post([FromBody]int accountId, [FromBody]string content, [FromBody]string paneId, [FromBody]string url) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Source: Parameter Binding in ASP.NET Web API : Using [FromBody]

Consider creating a model in the action server side

public class MyModel {
    public int accountId { get; set; }
    public string content { get; set; }
    public string paneId { get; set; }
    public string url { get; set; }
}

And update the action to expect that.

[HttpPost]
[Route("api/cms/")]
public IHttpActionResult Post([FromBody] MyModel model) { 
    //code removed for brevity
}

Upvotes: 4

Igor
Igor

Reputation: 62308

If you want to send a string as the body do the following:

  • Add the header: Content-Type: application/x-www-form-urlencoded
  • Change the string value in the body so it is prefixed with a = character: =5

Upvotes: 1

Related Questions