使用web api控制器MVC返回JSON
我正在尝试将我使用的常规旧控制器转换为API控制器,但遇到了一点困难。这一系列函数的作用是,在jQuery中,它迭代一个包含员工所有用户名的文件,并为每个用户名调用我的webapi控制器中的PopulateEmployee方法,该方法应返回JSON,然后填充一个results div 当手动导航到 ..domain../staffinfo/populateemployee/employeeusername 我得到了错误使用web api控制器MVC返回JSON,json,model-view-controller,asp.net-web-api,umbraco,asp.net-web-api-routing,Json,Model View Controller,Asp.net Web Api,Umbraco,Asp.net Web Api Routing,我正在尝试将我使用的常规旧控制器转换为API控制器,但遇到了一点困难。这一系列函数的作用是,在jQuery中,它迭代一个包含员工所有用户名的文件,并为每个用户名调用我的webapi控制器中的PopulateEmployee方法,该方法应返回JSON,然后填充一个results div 当手动导航到 ..domain../staffinfo/populateemployee/employeeusername 我得到了错误 This XML file does not appear to have
This XML file does not appear to have any style information associated with it. The
document tree is shown below.
<Error>
<Message>
The requested resource does not support http method 'GET'.
</Message>
</Error>
为api控制器设置的路由
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
指定使用“POST”的jQuery调用,请原谅此函数中递归调用的技巧
function getEmployeeObjectByIndex() {
$.ajax({
url: $('#root').val() + '/api/StaffInformation/PopulateEmployee',
type: 'POST',
async: true,
contentType: 'application/json, charset=utf-8',
data: JSON.stringify({ 'username': lines[i] }),
success: function (staffObject) {
if (!(staffObject.Name == undefined)) {
buildHtmlStrings(staffObject);
}
i++;
getEmployeeObjectByIndex(); //recursive call
}
});
}
手动导航到该地址会引发错误,因为手动导航时您正在执行
GET
(并且您的方法只允许POST
s)
您应该启动Fiddler并观看ajaxPOST
请求和响应,以查看服务器如何响应/您的请求如何发出
Web API有一个属性,即内容协商意味着您可以根据需要发送任何数据并接受任何数据
$.ajax({
//这是将您的数据类型json数据发送到服务器,在这里您可以发送任何类型的数据
accept: 'application/json',
//这是从服务器接收/获取数据到客户端。。。
//所以在这里你得到了JSON数据,因为你只想提到你想要的数据类型是什么。。。
//如果您发送xml并且想要json,那么只需将其写为json即可将其自动转换为所需的数据类型。..byMediaTypeFormatter
})) 我不清楚你的问题是什么。您是否在问为什么获取“请求的资源不支持http方法‘get’”?Jonathan回答了上面的问题。Checkout[[1]:您正在使用参数“username”传递数据,您需要控制器中的字符串id。然后您的路由web配置具有/{action}/{id}。也许将其更改为{id':行[i]}会有帮助吗?
contentType: 'application/json, charset=utf-8',
accept: 'application/json',