ASP.NET-MVC. Как получить название контроллера от URL?

Проблема, Вы просите, чтобы компилятор принял решение о намерении пользовательского кода. Возможно, я хочу, чтобы моя супер большая структура была передана значением так, чтобы я мог сделать что-то в конструкторе копии. Верьте мне, у кого-то там есть что-то, чем их законно нужно назвать в конструкторе копии для просто такого сценария. Переключение на касательно обойдет конструктора копии.

Наличие этого быть сгенерированным решением компилятора будет плохой идеей. Так как причина, то, что она лишает возможности рассуждать о потоке Вашего кода. Вы не можете посмотреть на вызов и знать то, что точно он сделает. Необходимо a) знать код и b) предположить компиляторную оптимизацию.

5
задан Gregoire 20 October 2009 в 03:22
поделиться

3 ответа

См. Сообщение в блоге Стивена Уолтера Совет № 13 по ASP.NET MVC - Модульное тестирование собственных маршрутов

В проекте MvcFakes есть старая ссылка на System.Web.Abstractions. Так что вы должны заменить его с новым и повторно перепрограммируйте проект, чтобы получить MvcFakes.dll.

Это мой код:

public string getControllerNameFromUrl()
{
    RouteCollection rc = new RouteCollection();
    MvcApplication.RegisterRoutes(rc);
    System.Web.Routing.RouteData rd = new RouteData();
    var context = new FakeHttpContext("\\" + HttpContext.Request.Url.AbsolutePath);
    rd = rc.GetRouteData(context);
    return rd.Values["action"].ToString();
}

В моем коде выше «MvcApplication» - это имя класса в Global.asax.

Удачи!

4
ответ дан 13 December 2019 в 19:30
поделиться

You should probably add another route like George suggests but if you really just need the controller value derived from the route you can do this in your controller action methods:

var controller = (string)RouteData.Values["controller"];
6
ответ дан 13 December 2019 в 19:30
поделиться

I'm not sure what you're asking, so if my answer's wrong, it's because I'm guessing at what you want.

You can always add another route to your Global.asax. That's often the easiest way to deal with cases 'outside of the norm'.

If you want to return a list of products, you'll use this route:

routes.MapRoute(
            "ProductList",         
            "{language}/{products}/{action}/",
            new { controller = "Products", action = "List", language = "en" });

You can also replace products with the more generic {controller} if more than one type of entity is going to use this route. You should modify it for your needs.

For example, to make this a generic route that you can use to get a list of any product:

routes.MapRoute(
            "ProductList",         
            "{language}/{controller}/{action}/",
            new { controller = "Products", action = "List", language = "en" });

What this does is that it creates a route (that you should always place before your Default route) that says, "For whatever the user enters, give me the controller and action they ask for". (Such as /en/Products/List, or /en/Users/List).

To visit that controller, you simply need to navigate to the following: yoursite.com/en/products/list. You can also use the HTMLActionLink to visit the controller.

<%=Html.ActionLink("Product", "List", new { controller = Products }, null ) %>

I'm writing this without my IDE open, so the ActionLink may have an error in it.

1
ответ дан 13 December 2019 в 19:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: