c# - asp.net MVC 控制器类可以同时返回 Action Method 和 Json 吗?
问题描述
感谢您抽出宝贵时间,我有一个简单的问题,在 asp.net MVC 应用程序中,控制器内部是否有可能连同返回 View (ActionMethods) 的一些方法一起充当(或返回)Json 作为 Web API(可能是从外部应用程序调用)。
只是试图做一个适当的分离,因此试图理解。
非常感谢。
解决方案
You can make an action function like an API. Try something like the this.
// Controller/Action
[HttpGet]
public ActionResult IAmSpecial()
{
if (Request.IsAjaxRequest())
{
string[] objects = new string[] { "Foo", "Bar" };
return Json(objects);
}
return View();
}
This will return the IAmSpecial
view if you browse to {domain}/{Controller}/IAmSpecial
while it will return a JSON result if you use an AJAX Http Get request on the same url.
推荐阅读
- docker - 无法使用新映像更新 Minikube 部署
- reactjs - Firebase 数据库抛出“Firebase 错误。请确保您的 Firebase 名称拼写正确”
- grep - Linux中的正则表达式
- ios - 在 CollectionViewcell 中实现 UIScrollView
- caching - Blazor 服务器应用程序中的应用程序范围数据
- node.js - 我有与我的 npm 构建相关的错误,并且开始找不到我的构建脚本和我的节点版本与全局版本不匹配
- java - 片段未打开 (Android/Java)
- python - 如何在 matplotllib 条形图的 x 轴上添加第二行标签
- docker - Docker 使用 GitBash / Cmder - 路径问题
- java - 我无法理解junit mockito测试中willThrow、doThrow的逻辑