通过Ajax将String Type数据传递给.NET GET WEB API

时间:2014-10-21 03:53:11

标签: asp.net-web-api

我曾经以这种方式编码并且工作正常:

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);
});

我有一个例外:

  

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

有人可以帮忙吗?我用谷歌搜索了一段时间,但所有的情况都与我不同。

非常感谢!

1 个答案:

答案 0 :(得分:0)

我认为optional parameters完全支持WebApi但不确定'FormatterParameterBinding也可以支持optional parameter

可能你可以删除[HttpPut] public object dispatchProduct(int id, [FromBody]string dispatchStatus) { if (dispatchStatus == null) { //..works same as before but without a exception } } ,你可以这样做

{{1}}