c# - 我可以简化此返回 View 的代码吗?显得很多余

标签 c# asp.net-mvc-3

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

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

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

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

编辑:感谢所有回复:)

最佳答案

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

public ActionResult Show(string viewName)
{
    return View(viewName);
}

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

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

需要 viewName 约束来防止此路由匹配任意 URL。

注意这是一个信息泄露漏洞;攻击者可以请求 /ControllerName/Show?viewName=~/Views/Secret/View
如果您有任何不使用模型的 secret View ,您应该在操作中验证 viewName
为此,您可以使用枚举,如 dknaack's answer .

关于c# - 我可以简化此返回 View 的代码吗?显得很多余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8719064/

相关文章:

c# - 避免在 Azure EventGrid 中将 DateTimeOffset 转换为 UTC 时间

c# - 标签在 OnDraw 事件中动态创建并可从 Visual Studio Designer 编辑

c# - wcf 接口(interface) : why doesn't it 'just' go to the methode but to the whole class

c# - 在 asp.net mvc 3 和 jquery 中记录帖子

c# - 如何配置 Simple Injector 以在 ASP.NET MVC 中运行后台线程

c# - 执行 EF Core 迁移(SmartEnum)时“找不到适合实体类型的构造函数”

c# - OData 路径模板不是有效的 OData 路径模板

asp.net-mvc - MVC3 使用值和名称填充下拉列表

asp.net-mvc - 复杂类型嵌套对象的绑定(bind)属性包含和排除属性

performance - 在 Nopcommerce 上构建的电子商务网站在多个主机名上从 CDN 加载图像的挑战