我试图将单个参数(字符串值)传递给 webapi Controller ,但是它不起作用。参数值到达 Controller 时为“null”。这是我的 WebApi 配置,
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}"
);
}
}
Controller :
[HttpPost]
public HttpResponseMessage GetDataView(string request)
{
try
{
var result = DB.GetDataView(request);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception ex)
{
//todo: log exception
throw ex;
}
}
AJAX
var serverName = 'ds100';
$.ajax({
url: 'api/ServerInfo/GetDataView',
type: 'POST',
dataType: 'json',
data: serverName,
success: function (data, textStatus, xhr) {
},
error: function (xhr, textStatus, errorThrown) {
}
我错过了什么吗?如有任何帮助,我们将不胜感激。
最佳答案
问题似乎出在你的ajax参数上,data
参数接收一个对象(json),该对象为你在请求中传递的每个值保存一个属性,我认为你应该使用
var serverName = 'ds100';
$.ajax({
url: 'api/ServerInfo/GetDataView',
type: 'POST',
dataType: 'json',
data: {request: serverName} ,
success: function (data, textStatus, xhr) {
},
error: function (xhr, textStatus, errorThrown) {
}
这样就可以了
关于javascript - 使用 jQuery Ajax 将单个参数传递给 WebApi Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514898/