[英]How to return Javascript from an ASP.NET 5 MVC 6 controller action
[英]Return JSON from any ASP.NET MVC controller action based on a parameter
在開發過程中,我經常這樣編寫控制器方法,以便確保模型的內容正確填充並有助於視圖的開發。
public ActionResult SomeMethod(int id, bool asJson = false)
{
var model = SomeBackendService.GetModel(id);
if(asJson)
return Json(model, JsonRequestBehavior.AllowGet);
return View(model);
}
一旦視圖開發完成,我就更改了它們,但是有時我發現自己希望以后可以將結果轉換為JSON。
理想情況下,我想設置一個Web.config密鑰,該密鑰允許將控制器方法請求為JSON,而無需為每個控制器重新編碼每個方法。 我希望以下方法在使用特定的querystring參數進行請求時以JSON形式返回模型。
public ActionResult SomeMethod(int id)
{
var model = SomeBackendService.GetModel(id);
return View(model);
}
我猜我需要走的路是實現自己的視圖引擎,但是我不確定那是正確的。
實際上,我想出了如何使用自定義DisplayModeProvider進行此操作。
我突然想到,我真正需要做的就是使用將呈現JSON的視圖。 因此,我創建了一個自定義DisplayProvider來覆蓋TransformPath方法:
public class JsonOnlyDisplayProvider : DefaultDisplayMode
{
public JsonOnlyDisplayProvider(string suffix) : base(suffix) { }
protected override string TransformPath(string virtualPath, string suffix)
{
return "~/Views/Shared/JsonOnly.cshtml";
}
}
然后,我修改了Global.asax中的Application_Start
方法,以使用ContextCondition插入新的提供程序來評估AppSetting和querystring參數。
protected void Application_Start()
{
DisplayModeProvider.Instance.Modes.Insert(0,
new JsonOnlyDisplayProvider(DisplayModeProvider.DefaultDisplayModeId)
{
ContextCondition = context =>
(context.Request.QueryString["asJson"] == "true" &&
!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AllowJson"]) &&
ConfigurationManager.AppSettings["AllowJson"] == "true")
});
}
最后一步是創建將生成JSON的通用視圖。 (當然,這種方法不會添加適當的標題...我願意接受有關如何進行排序的建議)
JsonOnly.cshtml
@{
Layout = null;
if (Model != null)
{
@Html.Raw(Json.Encode(Model))
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.