1. 程式人生 > 其它 >對於asp.net mvc post請求引數獲取小記

對於asp.net mvc post請求引數獲取小記

技術標籤:windowsmvc

1.普通Controller

在asp.net mvc專案中,我們自定義的controller都繼承自System.Web.Mvc.Controller。
對於post請求,排查了幾種獲取引數的方式,發現這種controller並不支援從body中讀取json串進行轉換成引數。故最後選擇使用FormCollection來獲取引數。

//需要前端以application/x-www-form-urlencoded格式傳輸引數
public ActionResult Test(FormCollection param)
{
	string test = param[
"test"]; return test; }

2.ApiController

在asp.net mvc中我們可以選擇建立Webapi專案。其自定義的controller都繼承自System.Web.Http.ApiController。
這種controller對於json格式的請求進行了支援,可以讀取到body中的json串並解析成引數,注意這裡需要json串與自定以的model對上。

//前端選擇使用application/json
public TestModel Post(TestModel testModel)
{
    return testModel;
}