我可以为返回视图简化此代码吗?这似乎非常多余

Tra*_*s J 6 c# asp.net-mvc-3

有没有办法将这些缩小为一组结果?我有一组像这样的页面,只返回静态内容,并认为必须有一个更有效的方法来做到这一点.

    public ActionResult Research()
    {
        return View();
    }

    public ActionResult Facility()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

编辑:感谢所有的回复:)

SLa*_*aks 9

您可以创建一个带viewName参数的共享操作方法:

public ActionResult Show(string viewName)
{
    return View(viewName);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将这些名称路由到此操作:

routes.MapRoute(
    "Simple Content",
    "/{viewName}",
    new { controller = "Something", action = "Show" },
    new { viewName = "Research|Facility|Contact" }
);
Run Code Online (Sandbox Code Playgroud)

viewName限制是必需的,以防止匹配任意URL这条路线.

请注意,这是一个信息泄露漏洞; 攻击者可以请求/ControllerName/Show?viewName=~/Views/Secret/View.
如果您有任何不使用模型的机密视图,则应viewName在操作中验证.
要做到这一点,你可以使用枚举,就像在dknaack的答案中一样.

  • 你打败了我.我认为这实际上不那么直观,而且可扩展性较低,我个人会将其保留原样(OP). (4认同)