[英]c# web api not working as POST Type
下面是我的API結構
public class CustomController : ApiController
{
[HttpPost]
public DataSet POSTM(string StaffCode, string bytearray, string Reason)
{
//Some Business logic Here
}
}
及其路線
config.Routes.MapHttpRoute(
name: "DefaultApi2",
routeTemplate: "api/{controller}/{staffCode}/{bytearray}/{Reason}",
defaults: new {
staffCode = RouteParameter.Optional,
bytearray = RouteParameter.Optional,
Reason = RouteParameter.Optional
}
);
我嘗試從jquery ajax調用它
var data = {
staffCode: staffCode_,
bytearray: bytearray_,
Reason: Reason_,
};
$.ajax(
{ url: 'http://localhost:59118/api/Custom/',
method : 'POST',
dataType: 'JSON',
data:data,
success: function (d)
{
alert("Saved Successfully");
},
error: function (e)
{
alert("Error please try again");
}
});
調用后,我在控制台日志中收到500 Internal Server Error
但是,如果我將[HttpPost]更改為[HttpGet],則效果很好
為什么它不能作為POST工作?
您正在使用POST
並在body
發送數據,則需要像這樣綁定模型
[HttpPost]
public DataSet POSTM(MyModel model)
{
//Some Business logic Here
}
和MyModel
將是一個類
public class MyModel
{
public string staffCode { get; set; }
public string bytearray { get; set; }
public string reason { get; set; }
}
保留默認的Web api配置路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
然后嘗試這樣稱呼它
var staffCode = "staff code here";
var bytearray = "hell byte arry";
var Reason = "no reason";
$.ajax(
{
url: 'http://localhost:51524/api/Test/POSTM/',
method: 'post',
data: JSON.stringify([staffCode, bytearray, Reason]),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert("Saved Successfully");
},
error: function (e) {
alert("Error please try again");
}
});
控制器看起來像這樣
[HttpPost]
public DataSet POSTM(List<string> data)
{
//ur code here
}
從Ajax發送數據時,
您的屬性“ staffCode
”與控制器方法屬性“ StaffCode
”不匹配。
屬性名稱區分大小寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.