问题
I'm working on providing friendly names for my MVC 4 controllers and I want to do something like the [ActionName="My-Friendly-Name"]
style, but for the whole controller.
I couldn't find any information about such an attribute, so how would I go about doing that? Also, will I need to add a new MapRoute to handle it?
EDIT:
For example, I'd like to route the following url:
http://mysite.com/my-reports/Details/5
be routed to the following controller:
[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);
}
}
}
回答1:
I don't know if there's answer to your question, but even if there were one, why in the world would you do such a thing? Why not do standard way : call the controller class anything you like (as long as it makes sense) and have it called by the framework for you? Why create two artificial naming conventions and map between them? I see not a single gain, but multiple cons. Such as - its harder to read, harder to maintain, harder to understand, it is also insignificant, but still, a strain on performance ...
Update
Please look into this posting, I think they did solve the problem that you're talking about.
- How to achieve a dynamic controller and action method in ASP.NET MVC?
Please let me know if it was of any help to you.
回答2:
Add a custom route that will match your specific name:
routes.MapRoute(
"MyCustomRoute",
"My-Friendly-Name/{action}/{id}",
new { controller = "ReportsController", action = "Index", id = "" }
);
Now every url that contains "My-Friendly-Name" for the controller will use your new route.
回答3:
Checkout this post, particularly where it talks about Route formatting.
来源:https://stackoverflow.com/questions/12539970/c-sharp-mvc-4-controllername-attribute