[英]Returning JSON with web api controller MVC
我正在嘗試將我正在使用的常規舊控制器轉換為 API 控制器並且遇到了一些困難。 這一系列函數的作用是,在 jQuery 中,它遍歷包含員工所有用戶名的文件,並且對於每個用戶名,它調用我的 webapi 控制器中的 PopulateEmployee 方法,該方法應該返回 JSON,然后填充結果 div。
當手動導航到 ..domain../staffinformation/populateemployee/employeeusername
我得到錯誤
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>
請注意,它將填充的 div 是 Umbraco CMS 頁面中的部分視圖,我認為這不是問題,但如果你們有不同的想法,請告訴我。
webAPI路由或其他東西我必須缺少一些東西。
謝謝你的幫助。
這是代碼。
請注意這個方法有 HttpPost 標簽
public class StaffInformationController : ApiController
{
[System.Web.Http.ActionName("PopulateEmployee")]
[System.Web.Http.HttpPost]
public StaffListing PopulateEmployee(string id)
{
//do error checking on input
StaffListing staffListing = new StaffListing(id);
//populate other fields
return staffListing;
}
}
為 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
)。
您應該啟動 Fiddler 並觀察 ajax POST
請求和響應,以查看服務器如何響應/您的請求正在發出
jQuery ------> web api
Web API 有一個屬性,即內容協商意味着您可以根據需要發送任何數據並接受任何數據。
$.ajax({
contentType: 'application/json, charset=utf-8',
// 這是將數據類型為 json 的數據發送到服務器,這里您發送任何類型的數據
accept: 'application/json',
//這是從服務器接收/獲取數據到客戶端... //所以在這里您可以獲取 JSON 數據,只要提及您想要的數據類型的數據... //如果您發送 xml 並且您想要 json 所以只寫接受為 json 它會自動轉換為您所需的數據類型..by MediaTypeFormatter
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.