Search code examples
jsonpostasp.net-web-apixdomainrequest

Cannot accept XDomainRequest POST to WebAPI


I have a controller class and I can initiate a Get call on the API but when I try a POST command I get HTTP/1.1 415 Unsupported Media Type

Is there somewhere that I have to allow POST? I placed [HttpPost] in front of the method but no luck.

public class initController : ApiController
{
    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    [HttpPost]
    public string Post([FromBody]string value)
    {
        oTree myT = new oTree();
        myT.build(0);
        myT.entity.question = value;
        return JsonConvert.SerializeObject(myT);
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    public void Delete(int id)
    {
    }
}

Javscript post code:

function gpRequest(service, verb, oData, callback) {
if (bool_cantransmit) {
    bool_cantransmit = false;
    var xdr;
    var url = base_service_url + service + "/";
    if (window.XDomainRequest) // Check whether the browser supports XDR. 
    {
        xdr = new XDomainRequest(); // Create a new XDR object.
        if (xdr) {
            xdr.onerror = errorHandler;
            xdr.onload = callback;
            xdr.contentType = "application/json";
            xdr.open(verb, url);
            xdr.send(oData);
        }
    } else {
        var xhr = new XMLHttpRequest();
        xhr.onerror = errorHandler;
        xhr.onload = callback;

        xhr.open(verb, url, true);
        xhr.send(oData);
    }
}

}


Solution

  • Well, value=Test is not a valid json. You could send a json format since you have setted application/json to the content-type header request property, for sample:

    gpRequest(service, 'POST', "{ Value: 'Test' }", callback);
    

    In the server side, try to create a DTO object:

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

    And get in on the post method:

    [HttpPost]
    public string Post([FromBody]MessageDTO message)
    {
        oTree myT = new oTree();
        myT.build(0);
        myT.entity.question = message.Value;
        return JsonConvert.SerializeObject(myT);
    }