5

I am developing group feature on asp.net application. I want to give users direct access to groups, so I want the url to be

www.<domain>.com/<groupname>

I implemented URL Routing for this case, but the problem that I want to pass the group name an to asp page as parameter, how can I do that?

the actual path is "~/Public/ViewGroup?group=<groupname> , how to get this group name and add it to the virtual path?

Thanks

3
  • I tried it, worked on local server but in production not. Commented Sep 4, 2011 at 11:48
  • It worked on production; after adding these to web.config <system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </handlers> </system.webServer> Commented Sep 6, 2011 at 4:36
  • Add the last configuration plus the configuration on system.web <compilation> <assemblies> <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </assemblies> </compilation> <httpModules> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </httpModules> Commented Sep 6, 2011 at 4:39

2 Answers 2

6

The quick answer is use:

routes.MapPageRoute(
   "groupname",
   "{group}",
   "~/public/viewgroup"
);

And then instead of (or as well as) using querystring to extract the value in ~/public/viewgroup code, you would instead extract the groupname from RouteData as follows.

ControllerContext.RouteData.Values["groupname"];

The other option is use the IIS rewrite module.

<rewrite>
    <rules>
        <rule name="groupname">
            <match url="^([^/]*)$" />
            <action type="Rewrite" url="public/viewgroup?group={R:1}" />
        </rule>
    </rules>
</rewrite>

If you really must pass the value as a new querystring value, and want to use Routing, then things get tricky. You actually have to define a custom handler and rewrite the path in order to append the routing values to the querystring.

public class RouteWithQueryHandler : PageRouteHandler
{
    public RouteWithQueryHandler(string virtualPath, bool checkPhysicalUrlAccess)
        : base(virtualPath, checkPhysicalUrlAccess)
    {
    }

    public RouteWithQueryHandler(string virtualPath)
        :base(virtualPath)
    {
    }

    public override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var request = requestContext.HttpContext.Request;
        var query  = HttpUtility.ParseQueryString(request.Url.Query);
        foreach (var keyPair in requestContext.RouteData.Values)
        {
            query[HttpUtility.UrlEncode(keyPair.Key)] = HttpUtility.UrlEncode(
                                               Convert.ToString(keyPair.Value));
        }
        var qs = string.Join("&", query);
        requestContext.HttpContext.RewritePath(
                             requestContext.HttpContext.Request.Path, null, qs);
        return base.GetHttpHandler(requestContext);
    }
}

This can be registered as follows:

routes.Add("groupname", new Route("{groupname}/products.aspx",     
           new RouteWithQueryHandler("~/products.aspx", true)));

It's quite a lot of work to avoid just pulling the value out to the Routing data.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm using .net 3.5, so I am using Map.add method routes.Add(new Route ("{groupname}", new GroupRouteHandler("~/Public/ViewGroup?group={groupname}") )); it gave me this error: ~/Public/ViewGroup?group={groupname}' is not a valid virtual path
Sorry my bad ? is disallowed, you can use a rewrite rule.
You can you this with routing as well, trying to find the right sytnax.
I found that I can extract it from the request url itself, but the main problem that it is not working on production, all methods work on local only!!!!
I didn't reachto a way to get paramters directly so I used, routes.Add(new Route ("{groupname}", new GroupRouteHandler("~/Public/ViewGroup") )); and in viewgroup page, I extracted the name from the url.
0

ASP.NET MVC path style arguments (parameters) can be accessed in C# controller like so. Path argument to be retrieved is "id" which returns a value of "123".

MVC Routing

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { id = RouteParameter.Optional });
}

//Test URL: http://localhost/MyProject/Test/GetMyId/123

MyController.cs

public class TestController : Controller
{
    public string GetMyId()
    {
        //ANSWER -> ControllerContext.RouteData.Values["id"]
        return ControllerContext.RouteData.Values["id"].ToString();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.