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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With