2
votes

I've created an Asp.Net Core Web Application and am looking to implement a Web API.

I've got a functional HttpGet implemented and am now trying to implement a HttpPost function:

    [HttpPost]
    public object Post([FromBody] object data)
    {            
        return null;
    }

I've tested this using Postman which worked fine. I set it up with json object in the body (set to raw and JSON (application/json)).

I get the expected response.

But when I try to call this from javascript using code suggested by Postman (or my own attempts):

    var settings = {
      "async": true,
      "crossDomain": true,
      "url": "http://localhost:51139/api/data",
      "method": "POST",
      "headers": {
        "content-type": "application/json",
        "cache-control": "no-cache",
        "postman-token": "999ee8ee-4e92-acb8-b7cf-144ffa49e5ee"
      },
      "processData": false,
      "data": "{\"Message\":\"This is body data\"}"
    }

    $.ajax(settings).done(function (response) {
      console.log(response);
    });

I get a "415 Unsupported Media Type" error.

Anyone see where I'm going wrong?

2
From where you call the javascript ? From a page ? From another Site ? - Max
I just have it in a simple html page which I open in a browser. There's no webserver or anything like that. - Dave Alger
If I run the code from a page on a simple webserver, I get the same response. - Dave Alger

2 Answers

3
votes

I had the same problem and tried a million different combinations ($.ajax, $.post etc), but what finally did it was the accepts: "application/json":

{
    type: "post",
    accepts: "application/json",
    url: "http://localhost:51139/api/data",
    contentType : "application/json",
    data: "{\"Message\":\"This is body data\"}"
}
0
votes

You could try something like this

[HttpPost]
public object Post()
{   
    Object o = Request.Form.First(o => o.Key == "data").Value 
    return null;
}

Then if you can create a class of that object you can use JsonConvert to Deserialize that object into the class object that you have created.