How do I route a URL with a querystring in ASP.NET MVC?

前端 未结 4 1731
有刺的猬
有刺的猬 2020-11-28 15:28

I\'m trying to setup a custom route in MVC to take a URL from another system in the following format:

../ABC/ABC01?Key=123&Group=456

The 01

4条回答
  •  猫巷女王i
    2020-11-28 16:17

    There is no reason to use routing based in querystring in new ASP.NET MVC project. It can be useful for old project that has been converted from classic ASP.NET project and you want to preserve URLs.

    One solution can be attribute routing.

    Another solution can be in writting custom routing by deriving from RouteBase:

    public class MyOldClassicAspRouting : RouteBase
    {
    
      public override RouteData GetRouteData(HttpContextBase httpContext)
      {
        if (httpContext.Request.Headers == null) //for unittest
          return null;
    
        var queryString = httpContext.Request.QueryString;
    
        //add your logic here based on querystring
        RouteData routeData = new RouteData(this, new MvcRouteHandler());
        routeData.Values.Add("controller", "...");
        routeData.Values.Add("action", "...");
      }
    
      public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
      {
         //Implement your formating Url formating here
         return null;
      }
    }
    

    And register your custom routing class

    public static void RegisterRoutes(RouteCollection routes)
    {
      ...
    
      routes.Add(new MyOldClassicAspRouting ());
    }
    

提交回复
热议问题