首页 > 解决方案 > asp.net MVC 控制器类可以同时返回 Action Method 和 Json 吗?

问题描述

感谢您抽出宝贵时间,我有一个简单的问题,在 asp.net MVC 应用程序中,控制器内部是否有可能连同返回 View (ActionMethods) 的一些方法一起充当(或返回)Json 作为 Web API(可能是从外部应用程序调用)。

只是试图做一个适当的分离,因此试图理解。

非常感谢。

标签: c#asp.net-mvcasp.net-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.


推荐阅读