C#MVC 4 ControllerName属性

joe*_*ish 7 c# asp.net-mvc asp.net-mvc-routing maproute asp.net-mvc-4

我正在为我的MVC 4控制器提供友好的名称,我想做一些类似于[ActionName="My-Friendly-Name"]样式的东西,但对于整个控制器.

我找不到关于这种属性的任何信息,那么我该如何去做呢?另外,我需要添加一个新的MapRoute来处理它吗?

编辑:

例如,我想路由以下网址:

 http://mysite.com/my-reports/Details/5
Run Code Online (Sandbox Code Playgroud)

被路由到以下控制器:

[ControllerClass="my-reports"]  // This attribute is made up.  I'd like to know how to make this functionality
public class ReportsController : Controller
{
    //
    // GET: /Reports/

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

    public ViewResult Details(int id)
    {
        Report report = db.Reports.Single(g => g.Id == id);
        return View(report);
    }

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

    [HttpPost]
    public ActionResult Create(Report item)
    {
        try
        {
            if (ModelState.IsValid)
            {
                item.Id = Guid.NewGuid();
                _context.Reports.AddObject(item);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(item);
        }
        catch (Exception)
        {
            return View(item);
        }
    }
Run Code Online (Sandbox Code Playgroud)

}

smi*_*rne 8

添加与您的特定名称匹配的自定义路由:

routes.MapRoute(
    "MyCustomRoute",
    "My-Friendly-Name/{action}/{id}",
    new { controller = "ReportsController", action = "Index", id = "" }
);
Run Code Online (Sandbox Code Playgroud)

现在,控制器中包含"My-Friendly-Name"的每个URL都将使用您的新路由.


Dis*_*ame -2

我不知道你的问题是否有答案,但即使有,你到底为什么要做这样的事情呢?为什么不采用标准方式:以您喜欢的方式调用控制器类(只要有意义)并让框架为您调用它?为什么要创建两个人工命名约定并在它们之间进行映射?我看到的不是单一的好处,而是多重的缺点。例如 - 它更难阅读,更难维护,更难理解,它也微不足道,但仍然对性能造成压力......

更新

请查看这个帖子,我认为他们确实解决了您所说的问题。

如果对您有帮助,请告诉我。