c# - MVC Action 名称作为常量字符串?

标签 c# asp.net-mvc

我创建了以下代码来尝试摆脱与 MVC 操作名称相关的任何魔术字符串。开发人员可能会更改访问修改器并在页面中访问它。

private const string IndexAction = "Index";
public ActionResult Index(){
    //do stuff
}
public ActionResult Other(){
    // do stuff
    if(foo)
        return RedirectToAction(IndexAction);
    //don't foo
}

我从来没有在任何地方见过这让我觉得这不是一个好主意,在编程世界中我怀疑我是第一个尝试这个的人。 问题: 将操作的名称放入不良做法是否会破坏 MVC 的任何原则。

最佳答案

基本上使用常量是个好主意(尽管根据我的经验,这在 MVC 中并不常见 - 如果您的 Controller 很小,也可能不需要)。按照您建议的方式,您可以将必须​​更改的点数从可能的几个减少到两个。

如果你想将它减少到一个点,你也可以使用 ActionName -attribute 也可以使用常量来分配 Action 的名称。这打破了 MVC 中使用的约定,因此其他人可能需要更长的时间来理解该系统,但具有将更改限制在一个位置的优势:

private const string IndexAction = "Index";

[ActionName(IndexAction)]
public ActionResult Index(){
    //do stuff
}
public ActionResult Other(){
    // do stuff
    if(foo)
        return RedirectToAction(IndexAction);
    //don't foo
}

有关 ActionName 属性及其用途的详细信息,请参阅 question及其答案。

关于c# - MVC Action 名称作为常量字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22010562/

相关文章:

c# - 如何在 C# 中将默认值设置为 propertyygrid 的大小类型属性?

c# - 与多个从站通信(基于 Modbus 协议(protocol))

c# - .net 事务范围 block 第二个事务

c# - MVC ActionLink 生成不同类型的链接……为什么?

c# - 将 IEnumerable<Inherited> 转换为 IEnumerable<Base>

javascript - ajax调用后为什么不能浏览到其他页面?

javascript - 我的数据库数据未显示在 jQuery 数据表中

c# - DataReader + MySql Connector + Dispose

C# MVC 3 : Prevent magic string in property attribute

c# - 如何在 ASP.NET Web 应用程序中处理在静态类中声明的资源