【问题标题】:Passing String Type data to .NET PUT WEBAPI through Ajax通过 Ajax 将字符串类型数据传递给 .NET GET WEB API
【发布时间】:2014-10-21 14:23:07
【问题描述】:

我以前用这种方式编码,效果很好:

C#:

[HttpPost]
public object Query([FromBody]string sql)
{
    // ...
}

Js:

$.ajax({
    url : "/api/controllerName/query",
    data : "=SELECT * FROM table1",
    dataType : "JSON",
    type : "POST",
    success : function(res){ console.log(res); },
    error : function(req, stat, err){ console.log(stat + ": " + err); }
});

所以现在我对 PUT API 以相同的方式执行此操作,但它不起作用:

C#:

[HttpPut]
public object dispatchProduct(int id, [FromBody]string dispatchStatus = "dispatched")
{
    // ...
}

Js

$.ajax({
    url: "/api/auction/dispatchProduct/2",
    type: "PUT",
    data: "=blablabla", 
    dataType: "JSON"
}).done( function createBiditem_doneHandler(result){
    console.log(result);
}).fail( function createBiditem_failHandler(req, stat, err){
    console.log(req);
    console.log(stat);
    console.log(err);
});

我遇到了一个异常:

{ "Message": "发生错误。", "ExceptionMessage": "可选 参数“dispatchStatus”不受支持 'FormatterParameterBinding'。", "ExceptionType": "System.InvalidOperationException", "StackTrace": null }

有人可以帮忙吗?我已经用谷歌搜索了很长一段时间,但所有案例都与我的不同。

非常感谢!

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    我认为WebApi 完全支持optional parameters,但不确定'FormatterParameterBinding 是否也能支持它。

    也许你可以删除那个optional parameter,你可以这样做

    [HttpPut]
    public object dispatchProduct(int id, [FromBody]string dispatchStatus)
    {
       if (dispatchStatus == null)
       {
            //..works same as before but without a exception
       }
    }
    

    【讨论】:

    • 你说得对,现在可以了,虽然我不知道'FormatterParameterBinding'。谢谢!
    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 2021-08-31
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2016-06-12
    相关资源
    最近更新 更多