如何注册在MVC6 RouteConstraints [英] How To Register RouteConstraints in MVC6

查看:216
本文介绍了如何注册在MVC6 RouteConstraints的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关于如何创建在previous MVC版本RouteConstraints许多教程:

There are numerous tutorials on how to create RouteConstraints in previous MVC versions:

  • Registering ASP.NET MVC Route Constraints for Attribute Routing
  • Constraints in Attribute-based Routing MVC5

这是如何工作,MVC6,特别是注册自定义路由约束,因此它可以在ApiController操作的属性来使用呢?

How does this work with MVC6, specifically registering the custom route constraint, so it can be used in attributes of ApiController Actions?

我创建了一个自定义路由约束,所谓的NonEmptyGuid,这真的只是确保一个非空的Guid用作的参数获取动作:

I have created a custom route constraint, called NonEmptyGuid, which really just makes sure a non-empty Guid is used as the parameter of a GET Action:

public class NonEmptyGuid : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection)
    {
        if (!values.ContainsKey(routeKey)) return false;

        if (values[routeKey].ToString().Equals(Guid.Empty.ToString())) return false;

        return true;
    }
}

问:
如何以及在哪里做一件注册这个定制RouteConstraint一个 MVC6 应用程序(例如,在这种情况下,一个项目的WebAPI)。

Question: How and where does one register this custom RouteConstraint for an MVC6 application (e.g. in this case in a WebApi Project).

推荐答案

您可以使用 RouteOptions 注册您的约束:

You can use RouteOptions to register your constraints:

services.Configure<RouteOptions>(options =>
                                options
                                .ConstraintMap
                                .Add("test", typeof(TestRouteConstraint)));

这篇关于如何注册在MVC6 RouteConstraints的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆