weixin_33724659 2018-03-08 14:11 采纳率: 0%
浏览 24

Web Api,ajax和内容类型

I would like to understand a little better about WebApi in Net and how is the correct way to called it with ajax. Little of info about my development environment: I am using .net 4.0 and visual studio 2010 and Jquery.

Model:

public class TestForm
{
    public string FirstName { get; set; }
}

WebApi:

public class TestpController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post(TestForm form)
    {
        string jose = "jose";
        return Request.CreateResponse(HttpStatusCode.OK, "yay");
    }
}

Client side:

V1 (doesnt work, return error 405 ):

$.ajax({
    url: "http://xxx/api/Testp",
    type: "POST",                   
    data: JSON.stringify({ FirstName: "Jose" }),                
    dataType: 'json',
    contentType: "application/json; charset=utf-8",                                 
    success: function(data) {
        console.log("success");
    },
    error: function (xhr, errorType, exception) {
        console.log("error");
    }
});

V2 (works):

$.ajax({
    url: "http://xxx/api/Testp",
    type: "POST",                   
    data: { FirstName: "Jose" },                
    dataType: 'json',
    success: function(data) {
        console.log("success");
    },
    error: function (xhr, errorType, exception) {
        console.log("error");
    }
});

Why do I get an error when I add contentType: "application/json; charset=utf-8" and change the data to JSON.stringify({ FirstName: "Jose" }), but it works when I removed the content type and send a object in data option.

  • 写回答

2条回答 默认 最新

  • weixin_33681778 2018-03-08 14:34
    关注

    Short answer lies in the output of these alerts:

    alert(JSON.stringify({FirstName :"Jose"}));
    alert({FirstName :"Jose"});
    

    The first one gives you a string, the second one gives you an object.

    Your method:

    public HttpResponseMessage Post(TestForm form)
    

    Accepts an object and not a string. So when you post a string, .NET Framework is not able to find a method which can process a string, hence returns 405.

    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题