![](/img/trans.png)
[英]How do I get MVC4 Web API to support HTTP Verbs and “Action” methods in the same controller?
[英]How do I declare an MVC 5 action like in Web API 2?
在Web Api中,我通常聲明如下操作:
[ResponseType(typeof(MyModel))]
public async Task<IHttpActionResult> Get(HttpRequestMessage request, int accountId)
{
//get myModel
return Ok(myModel);
}
我喜歡傳遞請求,而不是從控制器獲取請求。 MVC會做類似的事情嗎? 我一直在搜索,但找不到任何有關此功能的示例或參考。
編輯:另外,我想返回一個接口。 基本上我正在MVC中尋找這樣的東西:
[ResponseType(typeof(MyModel))]
public async Task<IActionResult> Get(HttpRequestMessage request, int accountId)
{
//get myModel
return View(myModel);
}
與MVC有點不同, Actions
映射到用戶交互,而不是直接映射到HttpRequest。 它們旨在傳遞Model
並使用View()
響應。 通常,您不需要檢查標題和方法類型之類的東西,因為您需要的是方法參數的一部分。 如果需要將View
作為特定方法類型的,則可以用[HttpPost]
或[HttpGet]
等[HttpGet]
。
您可以直接從控制器操作本身輕松通過靜態屬性HttpContext.Current.HttpRequest
獲取當前HttpContext。
不知道為什么不理會所有這些額外的事情,如果需要將其與Ajax一起使用,則只需返回對象的JSON。 用[HttpPost]
裝飾方法是否只需要發布。
// Home/Get/1 (use `id` in the constructor parameter)
// Home/Get/?accountID=1 (anything other than `id` in the constructor)
public JSONResult Get(int id)
{
//To get the Current Request, just start typing Request
Request.Browser();
MyModel myModel = Get.MyModel(id);
return JSON(myModel, allowget);
}
將其用作任務和發布。 我仍然不確定為什么我們需要這樣做,但是可以。
// FormVariable "accountID=1&userID=23"
[HttpPost]
public async Task<JSONResult> Get(int accountID, int userID)
{
//To get the Current Request, just start typing Request
Request.Browser();
MyModel myModel = await Get.MyModel(id);
return JSON(myModel);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.