如何构建仅用于操作的路由和具有id的控制器?

时间:2018-04-17 13:28:33

标签: asp.net asp.net-mvc routing asp.net-mvc-routing

我尝试构建两个仅用于操作的路由和一个带id的控制器,保持默认值。

我必须访问:

  1. www.mysite.com/MyController/MyAction/ {OptionalId}
  2. www.mysite.com/MyController/ {OptionalId}
  3. www.mysite.com/MyActionFromHomeController
  4. 我能够创建第一个和第三个点的路由,但不是第二个。目前的代码:

    timestamp =  1523966261 # Time.new.to_i
    math = timestamp / 30
    time_buffer =[math].pack('Q>')
    

1 个答案:

答案 0 :(得分:0)

我做到了!

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

        routes.MapRoute(
            name: "OnlyController",
            url: "{controller}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            constraints: new { id = @"\d+" } // define the id parameter needs to be integer
        );

        routes.MapRoute(
            name: "OnlyActionToHomeController",
            url: "{action}",
            defaults: new { controller = "Home" },
            constraints: new { noConflictingControllerExists = new NoConflictingControllerExists() }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

public class NoConflictingControllerExists : IRouteConstraint
{
    private static readonly Dictionary<string, bool> _cache = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var path = httpContext.Request.Path;

        if (path == "/" || String.IsNullOrEmpty(path))
            return false;

        if (_cache.ContainsKey(path))
            return _cache[path];

        IController ctrl;

        try
        {
            var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
            ctrl = ctrlFactory.CreateController(httpContext.Request.RequestContext, values["action"] as string);
        }
        catch
        {
            _cache.Add(path, true);
            return true;
        }

        var res = ctrl == null;
        _cache.Add(path, res);

        return res;
    }
}