代码之家  ›  专栏  ›  技术社区  ›  Colin Bowern

具有可为空类型的查询字符串路由

  •  0
  • Colin Bowern  · 技术社区  · 16 年前

    我有一天是编码员的禁闭日。我应该知道这一点,但我会寻求一些帮助。我有两条路线:

    /Login
    /Login?wa=wsignin1.0&wtrealm=http://localhost/MyApp
    

    使用HTTPGET访问第一个的action方法将返回登录页面,第二个页面将执行一些联合身份验证操作。我定义了两种控制器方法:

    public ActionResult Index();
    public ActionResult Index(string wa);
    

    当然,路由不喜欢这样,因为可以为空的类型使其不明确。如果路由数据中存在值,如何对其设置约束,使其只执行第二个方法?

    编辑:我用操作方法选择器暂时解决了这个问题。这是最好的方法吗?

    public class QueryStringAttribute : ActionMethodSelectorAttribute
    {
        public ICollection<string> Keys { get; private set; }
    
        public QueryStringAttribute(params string[] keys)
        {
            this.Keys = new ReadOnlyCollection<string>(keys);
        }
    
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            var requestKeys = controllerContext.HttpContext.Request.QueryString.AllKeys;
            var result = Keys.Except(requestKeys, StringComparer.OrdinalIgnoreCase).Count() == 0;
            return result;
        }
    }
    
    1 回复  |  直到 16 年前
        1
  •  0
  •   Yannis    16 年前

    我以前遇到过很多次这个问题,我认为这是一个经典的路由问题。我所做的是:

    在控制器中创建操作:

    public ActionResult Index();
    public ActionResult IndexForWa(string wa);
    

    在路由定义中执行所需的任何映射

    routes.MapRoute(
        "index_route",
        "Login"
        new {controller="Login", action="Index"}
    ); //This is not even necessary but its here to demo purposes
    
    routes.MapRoute(
        "index_for_wa_route",
        "Login/wa/{wa}",
        new {controller="Login", action="Index", wa = {wa)}
    );
    
    推荐文章