ASP.NET MVC, направляющий через [закрытые] атрибуты метода

Проверка простых чисел.

def is_prime(x):
    if x < 2:
        return False
    else:
        if x == 2:
            return True
        else:
            for i in range(2, x):
                if x % i == 0:
                    return False
            return True
x = int(raw_input("enter a prime number"))
print is_prime(x)
80
задан Leniel Maccaferri 11 March 2012 в 16:35
поделиться

5 ответов

ОБНОВЛЕНИЕ : Это было опубликовано на codeplex . Полный исходный код, а также предварительно скомпилированная сборка доступны для загрузки. У меня еще не было времени разместить документацию на сайте, поэтому этого сообщения SO на данный момент должно хватить.

ОБНОВЛЕНИЕ : Я добавил несколько новых атрибутов для обработки 1) порядка маршрута, 2) параметра маршрута ограничения и 3) значения параметров маршрута по умолчанию. Текст ниже отражает это обновление.

Я действительно сделал что-то подобное для своих проектов MVC (я понятия не имею, как Джефф делает это с stackoverflow). Я определил набор настраиваемых атрибутов: UrlRoute, UrlRouteParameterConstraint, UrlRouteParameterDefault. Их можно присоединить к методам действий контроллера MVC, чтобы автоматически привязывать к ним маршруты, ограничения и значения по умолчанию.

Пример использования:

(Обратите внимание, что этот пример несколько надуманный, но он демонстрирует эту функцию)

public class UsersController : Controller
{
    // Simple path.
    // Note you can have multiple UrlRoute attributes affixed to same method.
    [UrlRoute(Path = "users")]
    public ActionResult Index()
    {
        return View();
    }

    // Path with parameter plus constraint on parameter.
    // You can have multiple constraints.
    [UrlRoute(Path = "users/{userId}")]
    [UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
    public ActionResult UserProfile(int userId)
    {
        // ...code omitted

        return View();
    }

    // Path with Order specified, to ensure it is added before the previous
    // route.  Without this, the "users/admin" URL may match the previous
    // route before this route is even evaluated.
    [UrlRoute(Path = "users/admin", Order = -10)]
    public ActionResult AdminProfile()
    {
        // ...code omitted

        return View();
    }

    // Path with multiple parameters and default value for the last
    // parameter if its not specified.
    [UrlRoute(Path = "users/{userId}/posts/{dateRange}")]
    [UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
    [UrlRouteParameterDefault(Name = "dateRange", Value = "all")]
    public ActionResult UserPostsByTag(int userId, string dateRange)
    {
        // ...code omitted

        return View();
    }

Определение атрибута UrlRouteAttribute:

/// <summary>
/// Assigns a URL route to an MVC Controller class method.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteAttribute : Attribute
{
    /// <summary>
    /// Optional name of the route.  If not specified, the route name will
    /// be set to [controller name].[action name].
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Path of the URL route.  This is relative to the root of the web site.
    /// Do not append a "/" prefix.  Specify empty string for the root page.
    /// </summary>
    public string Path { get; set; }

    /// <summary>
    /// Optional order in which to add the route (default is 0).  Routes
    /// with lower order values will be added before those with higher.
    /// Routes that have the same order value will be added in undefined
    /// order with respect to each other.
    /// </summary>
    public int Order { get; set; }
}

Определение атрибута UrlRouteParameterConstraintAttribute:

/// <summary>
/// Assigns a constraint to a route parameter in a UrlRouteAttribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterConstraintAttribute : Attribute
{
    /// <summary>
    /// Name of the route parameter on which to apply the constraint.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Regular expression constraint to test on the route parameter value
    /// in the URL.
    /// </summary>
    public string Regex { get; set; }
}

Определение атрибута UrlRouteParameterDefaultAttribute:

/// <summary>
/// Assigns a default value to a route parameter in a UrlRouteAttribute
/// if not specified in the URL.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterDefaultAttribute : Attribute
{
    /// <summary>
    /// Name of the route parameter for which to supply the default value.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Default value to set on the route parameter if not specified in the URL.
    /// </summary>
    public object Value { get; set; }
}

Изменения в Global.asax.cs:

] Замените вызовы MapRoute одним вызовом функции RouteUtility.RegisterUrlRoutesFromAttributes:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        RouteUtility.RegisterUrlRoutesFromAttributes(routes);
    }

Определение RouteUtility.RegisterUrlRoutesFromAttributes:

Полный исходный код доступен на codeplex . Если у вас есть отзывы или сообщения об ошибках, перейдите на сайт.

одним вызовом функции RouteUtility.RegisterUrlRoutesFromAttributes:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        RouteUtility.RegisterUrlRoutesFromAttributes(routes);
    }

Определение RouteUtility.RegisterUrlRoutesFromAttributes:

Полный исходный код доступен на codeplex . Если у вас есть отзывы или сообщения об ошибках, перейдите на сайт.

с одним вызовом функции RouteUtility.RegisterUrlRoutesFromAttributes:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        RouteUtility.RegisterUrlRoutesFromAttributes(routes);
    }

Определение RouteUtility.RegisterUrlRoutesFromAttributes:

Полный исходный код доступен на codeplex . Если у вас есть отзывы или сообщения об ошибках, перейдите на сайт.

62
ответ дан 24 November 2019 в 09:59
поделиться

Этот пост предназначен только для расширения ответа DSO.

При преобразовании моих маршрутов в атрибуты мне нужно было обработать атрибут ActionName. Итак, в GetRouteParamsFromAttribute:

ActionNameAttribute anAttr = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), false)
    .Cast<ActionNameAttribute>()
    .SingleOrDefault();

// Add to list of routes.
routeParams.Add(new MapRouteParams()
{
    RouteName = routeAttrib.Name,
    Path = routeAttrib.Path,
    ControllerName = controllerName,
    ActionName = (anAttr != null ? anAttr.Name : methodInfo.Name),
    Order = routeAttrib.Order,
    Constraints = GetConstraints(methodInfo),
    Defaults = GetDefaults(methodInfo),
});

я также обнаружил, что именование маршрута не подходит. Имя создается динамически с помощью controllerName.RouteName. Но мои имена маршрутов являются константными строками в классе контроллера, и я использую эти константы для вызова Url.RouteUrl. Вот почему мне действительно нужно, чтобы имя маршрута в атрибуте было действительным именем маршрута.

Еще я сделаю преобразование атрибутов по умолчанию и ограничений в AttributeTargets.Parameter, чтобы я мог привязать их к параметрам.

3
ответ дан 24 November 2019 в 09:59
поделиться

1. Загрузить RiaLibrary. Web.dll и ссылка это в вашем проекте

2 веб-сайта ASP.NET MVC. Расшифровка методов контроллера с помощью параметра [Url] Attributes:

public SiteController : Controller
{
    [Url("")]
    public ActionResult Home()
    {
        return View();
    }

    [Url("about")]
    public ActionResult AboutUs()
    {
        return View();
    }

    [Url("store/{?category}")]
    public ActionResult Products(string category = null)
    {
        return View();
    }
}

BTW, '?' в параметре '{? category}' означает, что он необязателен. Нет необходимости указывать это явно в параметрах маршрута по умолчанию, что равно

routes.MapRoute("Store", "store/{category}",
new { controller = "Store", action = "Home", category = UrlParameter.Optional });

3. Обновить Global.asax.cs файл

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoutes(); // This does the trick
    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

Как установить значения по умолчанию и ограничения? Пример:

public SiteController : Controller
{
    [Url("admin/articles/edit/{id}", Constraints = @"id=\d+")]
    public ActionResult ArticlesEdit(int id)
    {
        return View();
    }

    [Url("articles/{category}/{date}_{title}", Constraints =
         "date=(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])")]
    public ActionResult Article(string category, DateTime date, string title)
    {
        return View();
    }
}

Как установить порядок? Пример:

[Url("forums/{?category}", Order = 2)]
public ActionResult Threads(string category)
{
    return View();
}

[Url("forums/new", Order = 1)]
public ActionResult NewThread()
{
    return View();
}
9
ответ дан 24 November 2019 в 09:59
поделиться

Я объединил эти два подхода во франкенштейновскую версию для всех, кто этого хочет. (Мне понравилась необязательная нотация параметров, но я также подумал, что они должны быть отдельными атрибутами от значений по умолчанию / ограничениями, а не смешанными в один).

http://github.com/djMax/AlienForce/tree/master/Utilities/Web/

0
ответ дан 24 November 2019 в 09:59
поделиться

Мне нужно было заставить маршрутизацию ITCloud работать в asp.net mvc 2 с использованием AsyncController - для этого просто отредактируйте класс RouteUtility.cs в исходниках и перекомпилируйте. Вы должны убрать "Completed" из названия действия в строке 98

// Add to list of routes.
routeParams.Add(new MapRouteParams()
{
    RouteName = String.IsNullOrEmpty(routeAttrib.Name) ? null : routeAttrib.Name,
    Path = routeAttrib.Path,
    ControllerName = controllerName,
    ActionName = methodInfo.Name.Replace("Completed", ""),
    Order = routeAttrib.Order,
    Constraints = GetConstraints(methodInfo),
    Defaults = GetDefaults(methodInfo),
    ControllerNamespace = controllerClass.Namespace,
});

Затем, в AsyncController, украсьте XXXXCompleted ActionResult знакомыми атрибутами UrlRoute и UrlRouteParameterDefault:

[UrlRoute(Path = "ActionName/{title}")]
[UrlRouteParameterDefault(Name = "title", Value = "latest-post")]
public ActionResult ActionNameCompleted(string title)
{
    ...
}

Надеюсь, это поможет кому-то с такой же проблемой.

0
ответ дан 24 November 2019 в 09:59
поделиться
Другие вопросы по тегам:

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