开发者

Best way to generate url via Page.GetRouteUrl in a helper class?

开发者 https://www.devze.com 2023-01-23 22:09 出处:网络
I have just added routing in a new asp.net 4 web forms application, and have got my route table set up ok and page requests are working fine.

I have just added routing in a new asp.net 4 web forms application, and have got my route table set up ok and page requests are working fine.

What I now want to do is use the Page.GetRouteUrl method whenever I need to generate one of my seo friendly Url's. I started to implement this across various pages then thought it might cut down on code a bit if I had a method in one of my own helper classes, that constructs this url (using the Page.GetRouteUrl method) as I might have several parameters that need to be specified against the Page.开发者_如何转开发GetRouteUrl method each time.

However, within my helper class, it doesn't know what 'Page' is. I was thinking I could pass in 'Page' from the page that wants a routed url to be generated, but in some cases I want to construct one of these Url's in another class which doesn't know what 'Page' is, and in that scenario wouldn't be able to pass it in as a param (and therefore wouldn't be able to use the Page.GetRouteUrl within my helper class).

What is the normal approach when wanting to use Page.GetRouteUrl within classes that don't have an instance of the Page object?


You can pass Page as a constructor parameter, or this is actually the page reference:

var page = HttpContext.Current.Handler as Page;

You can cast it to the page type. Depending on the type of requests you are making, it may not always be page (say from a web service call, etc.).

HTH.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号