Thursday, July 24, 2008

URL Rewriting with URLRewriter.Net Simplest Way

URL Rewriting with URLRewriter.Net

URL Rewriting has lots of benefits, listing its main benefits

  • SEO Friendly URL
  • Secured URL
  • No need to change bookmark with change in site structure.

Before URL Rewriting my URL looks like
http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1

After URL Rewriting URL is changed to

http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx


Lets Understand URL Rewriting with Simple Example

A Website displaying articles list in a gridview on clicking the article link, it will display dynamically generated article content.

Before URL Rewriting when you mouse-over 1st Article Link, "Asp.net Website Path" it uses query string to display the article content.


Dynamic page display Querysting, before URL Rewriting.



After URL Rewriting we will achieve how SEO Friendly URL is used to display article content.


Now, lets understand how we can achieve it.

For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net

Step-by-Step Explanation

Step 1: Download Binary Files for URLRewriter.Net

Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.


Step 3: Update Web.Config File to make URLRewriter.Net works.
<configuration>

<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
</httpModules>

</system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
</modules>

<validation validateIntegratedModeConfiguration="false" />

</system.webServer>

<rewriter>
<rewrite url="~/Article/(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2"/>
</rewriter>

</configuration>


Step 4: Adding Function to Generate SEO Friendly URL from given Title


public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}


Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.
Note: Learn more about DataBinder.Eval Function



<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="788px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:HyperLink ID="hlTitle" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Title"),DataBinder.Eval(Container.DataItem,"Id"))%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>


Now, Lets Check the stuff so far developed.

Assigning SEO Friendly URL in to grid.


On clicking URL inside grid it will point to Dynamically Generated Page with SEO Friendly URL, rather than QueryString.


Things to consider while URL Rewriting.

Problem 1: Page Postback, will turns User Friendly URL into Original URL.
Problem 2: CSS, Image Files pointing to URL Rewriting Page won't work, as they might be pointing with absolute path.

Problem 1: Page Postback for Page displaying URL Rewritten URL
Page Postback of Page displaying User friendly URL will turns into original state when same page postback occurs. In our example, I am adding one button and trying to make Page Postback. You will notice that Page Postback will turns the User Friendly URL into original URL containing QueryString.


For Resolving Page PostBack problem for Page displaying URL Rewritten URL

This article is inspired from Scott's URL Rewritten article. Adding two files as mentioned by scott. If you are developing code in VB download files from Scott's article, else for C# download files with Sourcecode at the end of this article.



Now, lets test the Page Postback by clicking on Button, you will notice this time, URL remains the same.




Problem 2: Image Display Problem
Now, lets display image on for this page and lets observe what problem we may run into. I have added following line to display image, but it won't works.

<img src="Images/article.gif" />


Resolve Problem, by refrencing file from root.
<img src="../Images/article.gif" />



Download Source-Code for URL Rewriting

100 comments:

Anonymous said...

It is nice article. I was looking for tutorial on URLRewriter.Net and it was useful to me, but i am confuse whether we should use hypen "-" or underscore "_" for replacing space while making url seo friendly. Thanks for sharing.

Anonymous said...

use the - instead of _

Anonymous said...

Its a perfect solution i was searching for url rewriting for asp.net application. Can you update your article to show how can i handle multiple or two or more querystring value to handle url rewriting request.

Its a easiest solution i came across and more practical to what i am looking for.

Anonymous said...

this example wokring on local server well but when i am moving on pre production server is not wokring giving me "HTTP Error 404 - File or directory not found."
is any setting in IIS 6.0 for using this urlrewriting..
Please help me out ASAP.
Thanks
Dinesh

DotNetGuts said...

Can you describe all your problems in step, because i have tested and it should work fine everywhere until there is some firewall settings which is affecting your code...

Anonymous said...

thanx

Anonymous said...

Finally I found perfect URL Rewriting solution. Thanxs

Anonymous said...

It would be nice, IF I could actually get it to work.

[NullReferenceException: Object reference not set to an instance of an object.]
Intelligencia.UrlRewriter.Configuration.RewriterConfiguration.Load() +102
Intelligencia.UrlRewriter.Configuration.RewriterConfiguration.get_Current() +169
Intelligencia.UrlRewriter.RewriterHttpModule..cctor() +47

[TypeInitializationException: The type initializer for 'Intelligencia.UrlRewriter.RewriterHttpModule' threw an exception.]

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +1051
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +111
System.Web.Configuration.Common.ModulesEntry.Create() +39
System.Web.Configuration.HttpModulesSection.CreateModules() +164
System.Web.HttpApplication.InitModules() +28
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +729
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +298
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +107
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +289

DotNetGuts said...

Can you provide more details about how you have received error?

Gak Ada said...

When i using URLRewriter, i have error in Session, even if i set session to 1000, after 1 minutes, i dont do nothing, the session, still expired..
do you know how to handle it ?

thx

DotNetGuts said...

I don't think that Session can create problem, I strongly feel that you might be setting up or may be session value is overridden somewhere in project. One tip, why don't you search for "session" - ctrl+shift+f (In entire solution) it will give you all the places where session is declared and you can verify it.

Anonymous said...

Thanks it was useful, Finally I can able to write URL Rewriting. I have tried searching on URLRewriter Tutorial, but this article is perfect and helpful.

Unknown said...

Dear Sir.
I'm one of who read this article as bible for url-rewriting.
It's perfect and really good for me, but problem was it's fine on my local but not on the pre-production server (like Dinesh said in earlier posting)

I know you said him to check firewall, and he said "thnx" but for me ... :(
Actually I'm using GoDaddy.com as pre-production server, and no way to get to know if firewall is on.

This problem makes me crazy for 1 week.
I'll really appreciate if you let me know any other hint that might cause this problem, or any experience with GoDaddy.com like "hey, the firewall is on there!".

Plz reply me... plz.

DotNetGuts said...

@YongHyok,

Hi YongHyok,

I am not sure about root cause of problem, as you are telling it is running in your local, but it is not running on godaddy server.

1) Do one thing, ask GoDaddy Customer Care, do they support (Url Rewriter), to best of what i know answer is Yes.

2) Try to deploy your website again, There might be possibility you have made some changes on production server, and it is cause of problem.

3) Check your web.config file do they contain proper changes and it is applied correctly.

4) Try to take help of GoDaddy Technical Team, they are the expert and can help you out in seconds of what is going wrong.

5) Incase none of them works, please state your problem, I will be happy to solve your problem. As it is running perfect for me.

Cheers,
Happy Coding.

Unknown said...

Dear Sir.

I really appreciate your instant reply.

Seems making funny, but, while I was trying to solve this problem, my client changed hosting company.

But still not working, and right now I can't ask to support.

Actually I don't think I made mistake while uploading to server.

I'll not be able to thank you enough if you check my sample code.
(I want you to let me know your email account. My email account is stormbreaker18@gmail.com)

Thanks indeed, and Best Regards.

Unknown said...

Its a very easy & perfect solution for URL Reriting.
How can we use this for multiple query strings?

DotNetGuts said...

Hi Pintu,

You can check out this blog to handle multiple querystring request while Url rewriting.

http://dotnetguts.blogspot.com/2009/01/multiple-querystring-for-url-rewriting.html

DotNetGuts said...

@aloneguid

Yes i have it on my machine working perfect.

Anonymous said...

Hi,

How would you solve the image problems if you are using web user control, and on some of the cases the control is located in the root and on others in subfolder?

On the same note, I'm having this problem also with links....

Thanks.

DotNetGuts said...

@beytz,

Check out following blog post about asp.net website path

Anonymous said...

I did exactly as written here but for some reason i get this error:

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Unrecognized configuration section rewriter.

DotNetGuts said...

Parser Error: can occurs mainly due to error in code, try downloading my sourcecode files and check what went wrongs

According to me, You haven't copied all code to web.config or used wrong section

Anonymous said...

Yeah very useful article. I've enable Url Rewritting for my blog in 10 minutes following your post ! Many thks

Just a tips, for a good google indexing you must include date of article in url !

Grygorii said...

It is cool. But his did not work, when used Login. When I clicked button at Login, page return not rewrite url :(

DotNetGuts said...

@Программист
When Page is Postback User friendly URL will turns into original state, so to avoid that you need to Add Two Files as instructed above in article.

By the way, why you want to rewrite url for login page, don't get logic behind rewriting login page?

Grygorii said...

Sorry I not correct say. I used Web Control "Login" <asp:Login ID="Login1" runat="server"> And I add two files in my project FormRewriter.cs and Form.browser. And action in forms tag get rewrite url. And when I used any other web control sort of works. But when I clicked Login Control, not work.
I used Login control how block authentication
Sorry for my English

Unknown said...

Great stuff. The only actual sample I saw. I used it as a base for my own sample in vb.net using the Northwind SQL Server database. See http://www.corobori.com/Blog/es/post.aspx?id=5d13a0d4-6882-4154-85de-dd4687a62c6f

Unknown said...

Dear Sir,

I use your example of re-write and it working on first time page load event,but in the time of fire a page event (like button click) it not working properly.
It show actual Page url.
I am using Asp.net 2.0 and ajax control tool kit.
Waiting for your early reply.

Debayan

DotNetGuts said...

@Debayan

Please read the whole article, In last part i have explained how to handle page postback with url rewriting.

Anonymous said...

Hi,

I m trying to implement URL rewriting.

I downloaded the code and run the code from Visual studio 2005.The example is working fine.

but when i created the virtual directory in IIS and tried to access its throwing page not found error.

and when i configured "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" in IIS,i m getting following error,

Server Error in '/URLRewrite25' Application.
--------------------------------------------------------------------------------

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /URLRewrite25


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

Am i missing anything here.
Plz help me out to solve the problem.
Awaiting for the early responses..

Thanks & Regards,
Srinivasan P

Anonymous said...

Dear sir,

Thank you for your co-operation.
My problem has been solved.
Many many thanks.

Debayan

Kevin said...

This works perfectly:

http://localhost:27390/607/folder/interesting-text-92.aspx

However, adding a dash to the folder path, e.g.:
http://localhost:27390/607/great-folder/interesting-text-92.aspx

results in an infinite redirections.

Suggestions?

Web.config:
rewrite url="~/(.+)-(.+).aspx" to="~/default.aspx?cid=$2"

DotNetGuts said...

@Kevin

You should add folder path in web.config.

rewrite url="~/great-folder/(.+)-(.+).aspx" to="~/default.aspx?cid=$2"

Unknown said...

Dear Sir

I have a question for using URLRewriter.net in ZenCart.

Please have look at this page http://www.purpleculture.com/a-photographic-guide-to-birds-of-china-b-34ed6c52ab37.html. There is a "add this to my cart" button in this page, when clicked, the URL will be changed into http://www.purpleculture.com/a-photographic-guide-to-birds-of-china-b-34ed6c52ab37.html?action=add_product.

I've added the following rule
rewrite url="~/(.*)-b-(.+).html(.*)?$" to="~/index.php?main_page=product_book_info&products_id=$2${encode($3)}" , but the "?action=add_product" part doesn't work. Do you have any idea?

Thanks
Davis

Anonymous said...

Is it possible to generate two different URL?

I have two datalist each pointing in different table in db. Both would then lead to different page to display data.

Would be great if someone could show me how to change .cs file so that can have two GenerateURL.

Thanks

Nicola said...

nice article!!
its all ok... or almost..
i can see images and template design .css.. why??

i have vista and iis 7.0..
is it the problem??
can u help me????

thank u
nicola

San Miguel said...

On local host test, you can add urls like index.html = default.aspx, or mysite.com/section/ = section.aspx. But on goddady hosting you only can add urls that finish it with aspx extension.

Anonymous said...

Hi

I have an application where a user logs in and becomes authenticated. On pages where the url has not been rewritten, the request shows as authenticated. On the url rewritten pages, however, the authentication cookie is present but IsAuthenticated returns false. I can browse back to the non rewritten page and is shows correctly as true. It definitely appears related to url rewriter. AS you can imagine this messes up any controls that use templates for logged in users. Any ideas?
Thanks

Naresh said...

Where to writ geenerateURL function??? please help me Im new to this .net ..Soon pls

DotNetGuts said...

You can write this GenerateURL Function on .aspx.cs page where you are actually generating url. You can also write this function in utility class and call the function from there.

Download code for URL Rewriting at the end of this article.

Danny said...

Seems like i have same poblem Программист had. When i signin using Login Control, the urlrewriter dont work. To resolve this i have to use Redirect after login but it isnt userfriendly ;). Any ideas how to fix this? Mayby smth in FormRewriter.cs ?

Anonymous said...

I am using master page and theme for my application. I am using logo of the website on master page. And tried your method of calling image from root. "../images/logo.gif" but it is not working.

Help me. Thanking you in advance.

DotNetGuts said...

You should follow this link to resolve Master Page Image display Problem http://dotnetguts.blogspot.com/2008/06/master-page-image-display-problem-and.html

Jony Shah said...

Hi.
i have implemented this and its working in local.now i have uploaded it on server but its giving me error like this :



The page cannot be found
The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.

Please try the following:

* Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.
* If you reached this page by clicking a link, contact the Web site administrator to alert them that the link is incorrectly formatted.
* Click the Back button to try another link.

HTTP Error 404 - File or directory not found.
Internet Information Services (IIS)

Need your help.
please reply.

DotNetGuts said...

@Jony,

404 - Page Not Found Error, can occur when URL Rewriting is not properly done. To best of my knowledge if it works in local it should work on Server too, unless you have hard-coded URL.

Use Relative path everywhere rather than absolute path.

Example: If you have Path which is like http://dailyfreecode.com/Forum/This-is-sample.aspx

Than change that with

~/Forum/This-is-sample.aspx

Now no matter on what server or computer you try to view this page, it will always displays.

In case if it still doesn't work than send me exact steps and code of how you are trying to do URL Rewriting.

prabir said...

hi,
is it possible to rewrite to a totally different domain.

DotNetGuts said...

Rewrite url is independent of domain, it would automatically acquire domain name from which response is generated.

Jony Shah said...

hi prabirshrestha
As i have never tried that.
But i have done with single domain succeessfully.so i can help you in that case.

prabir said...

this is my stuff in web.config
<add key="/rewrite.net/test.aspx" value="http://www.prabir.me" />
It should rewrite (not redirect) to prabir.me domain which is totally differnt domain. when i go to type http://www.olddomain/rewrite.net/test.aspx yelow screen of death comes saying "The given path's format is not supported."
Is my rule correct?

EveningStar said...

i have similar problem. it works great on my local PC. but i got page not found error once i post it to the server. not sure whether it due to .net version. I use .net 3.5 for the project.

DotNetGuts said...

@EveningStar

YOU NEED TO UNDERSTAND THAT IF YOU INPUT GARBAGE IT WILL RETURN GARBAGE, SO IF YOU ARE BUILDING HARDCORE URL INSTEAD OF RELATIVE URL, THAN YOU WOULD DEFINITELY FACE THIS PROBLEM. Try to form Relative path while creating url, and it would run good on server too.

Nick said...

Pardon me, what we should do if we want url without extension ".aspx" like this "http://site.com/category/4" on IIS 6? Is it forbidden behavior?

Jony Shah said...

hiii EveningStar

i think there is not a problem of version of .Net.

you have to make some setting in your IIS.

Do one thing give me your email id. I will send you mail for iis settings.

It may help you.

Regards
Jony Shah

Jony Shah said...

hiii Nick

yes we can do that.i have done that in my one module.i have made my URL somethng like this

http://localhost/Couponweb/Stores/LuggageGuru

you want like this.m i rite?

Regards
Jony Shah

Nick said...

2 Jony Shah
Yes, I have wrote my own module which catches the 404 error from IIS 6 and uses the "action" attribute of the html form. I stuck at postback. Everything works fine, but when user doing postback in browser he seeing url like "http://site.com/404.aspx?404;http://site.com/category/4" because this "dirty" url situated in the "action" attribute. This is bad but it works.
How you handle this problem?

Polix said...

Hello,
Great article. I have implemented url rewriting on my test page in the same way as it was written in article. All works good. But when I hook up existing sites to master page the default.aspx is not hidden in address bar. Withoud master page, the default.aspx is invisible in address bar. Except this unhidden default site name, all works good with master page. I suppose that it is connected with Form.browser but my knowledge of asp.net is insufficient to find solution myself. Did anybody of You meet this problem? How to handle this?

Best regards
Polix

Murugan said...

Nice Article
Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks
Nice Article

TW said...

Hi,

I have this rule
url="~/start/(.+).aspx" to="~/folder/page.aspx"

the initial url is:

www.mydomain.com/start/MyPage.aspx

Now, I may have any of these
www.mydomain.com/start/MyPage.aspx-1
www.mydomain.com/start/MyPage.aspx-1-2
www.mydomain.com/start/MyPage.aspx-1-2-abc

which i want to be wrtitten as:
"~/folder/page.aspx?sid=1&rid=2&pw=abc

the URL may have 0-3 querystring params.


How can I specify this in a rule/s?

I've tried
rewrite url="~/start/(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2"
rewrite url="~/start/(.+)-(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2&pw=$3"
rewrite url="~/start/(.+)-(.+)-(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2&rid=$3&pw=$4"

which is not working.

Thanks

DotNetGuts said...

Following won't work, as your first rewrite url supress rest of them.

rewrite url="~/start/(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2"

rewrite url="~/start/(.+)-(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2&pw=$3"

rewrite url="~/start/(.+)-(.+)-(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2&rid=$3&pw=$4"


Solution.
1. Follow instruction in this article for url rewrite with multiple querystring http://dotnetguts.blogspot.com/2008/06/master-page-image-display-problem-and.html


2. Change the order of rewrite url from bottom up approach. That is url which has maximum number of query string should come first in sequence and one with less no. of query string parameter turns after that.

So being said that you need to change order of rewrite tag in web.config file to following

rewrite url="~/start/(.+)-(.+)-(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2&rid=$3&pw=$4"

rewrite url="~/start/(.+)-(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2&pw=$3"

rewrite url="~/start/(.+)-(.+).aspx" to="~/folder/page.aspx?sid=$2"

led said...

And if i want to use this with search parameters from a form?
Is it possible?

led said...

How can i use this with hyperlinks
i can't assign the function generateURL to a hyperlink

DotNetGuts said...

You can use

hlUserName.NavigateUrl = GenerateUrl();

led said...

thanks, thanks, thanks

Unknown said...

Hello Sir,
In the application, I have a folder named Shops. When I enter
http://localhost:2141/sample/Shops/shopname/ it should go to the detail page of particular shop. The rule I have put like this
rewrite url="^~/Shops/(.*) to "~/Shops/detail.aspx?Id=$1"
But the thing is that when the user type in http://localhost:2141/sample/Shops/ i want to redirect it to http://localhost:2141/sample/Shops/default.aspx . But now this is also redirecting to http://localhost:2141/sample/Shops/shopname/
Could you plz suggest a solution?

DotNetGuts said...

@Divya

Change the sequence of rewrite url in web.config file.

Check the following comment for more info.
http://dotnetguts.blogspot.com/2008/07/url-rewriting-with-urlrewriternet.html?showComment=1253265226341#c2806447757121148555

felipevanc said...

Sir,

The article is excelent.I haveeverything running fine locally.
However,when Ideploy it in my dedicated server it says "HTTP Error 404 - File or directory not found."

I found this happens to other people here and many others in other forums. Does someone find a turn around for this problem? Could it be a configuration in the IIS or something like that?

thanks a lot!!

felipevanc said...

I found the solution to why it wasn't working in the production server. Just have to configure the IIS like this http://urlrewriter.net/index.php/support/installation/windows-server-2003

Jesper C said...

As I see, there is a problem with the url rewriter.

If you add in web.config:
rewrite url="~/thanks/" to="~/thanks.aspx"/


www.domain.com/thanks/ works fine...
but
www.domain.com/thanks/tesdt/test also points to thanks.aspx

If the user writes: www.domain.com/thanks.aspx, he enters the orginal page, how to redirect him to domain.com/thanks/
?

Any suggessions to solve the problems?

Anonymous said...

What about Grids that filter based on querystrings?

I may have missed something since I am quite tired at the moment. but when loading the rewritten URL my grid remains unfiltered because it requires a querystring to filter results. How can you order the gridview to treat an integer in the document name as if it were a querystring?

Anonymous said...

Never Mind, that previous post can be attributed to running out of ADD medication.

asder43 said...

Hi,
link for UrlRewriter.Net seems
dead. Can you please upload it again..
Thanks,
Nicely formulated article btw!

Unknown said...

HI,

I want to do similar thing in sharepoint. IN that whenva I m trying to click default links it is showing original url not the one I want.So how I can use form browser in it.

Any Idea how to achieve this.

Thanks,
AB

Unknown said...

Hi,

I've got a problem as follows:

I have two urls http://mysite.com/about-us and http://mysite.com/test

I've successfully setup urlrewriter and works well for about-us alias, however test is not defined. WHen I try to access test I get 404 http status.

Now I've enabled and redirect 404 http statuses to my custom file. THis works fine for urls with file extensions but for test above, I get the default 404 error page.

I've checked the urlrewriter site and it suggests I use:



I'm not an asp.net expert so not sure whether I've placed this in the wrong place of web.config. Can anybody point me in the right direction?

Thanks in advance!

Unknown said...

Hi,

I tried rewriting url, it works fine on my local machine, when i uploaded the website onto the production server i am getting the following error ;

Server Error in '/' Application.
--------------------------------------------------------------------------------

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /issue/current-issue.aspx

Please help me to solve this problem.

thanks in anticipation

Harish

DotNetGuts said...

Hello Everyone,

I am getting lot of email about saying that their URL Rewriting is working good in Local Environment, but when it goes to Production Environment it is giving 404 - Page Not Found Error

Solution
------------
1) Please don't use hard-coded url
2) Play with URL Rewriting Path, their is nothing wrong with any other part of URL Rewriting as it is running in Local
3) Try to use ResolveUrl() function while generating link.

I am using this piece of code on many of my development work and it is working like charm.

Unknown said...

Hi All,

People who are facing 404 - Page not found error, your attention please. I was facing this problem after uploading the website onto the production server and spent lots of my time trying to get away with this error, i also posted my query in this forum. Ultimate i found that you need to set the property runAllManagedModulesForAllRequests="true" of module element in web.config file. I started programming for the website and when i need the url rewrite solution i came accross this article since i already had web.config file in my project i did not copy the entire web.config from this article but copied required elements from the web.config mentioned here. But fogot to set the above mentioned property of module element. Which may be the case with everyone who are facing the Page not found error. All you who are facing this error, i request them not to foget to set the runAllManagedModulesForAllRequests="true" in module element. We tend to forget this which is very important else the url rewrite not work.

This article was wonderful and it works like char in the production server. My special thanks to the author of this article. Hope my suggestion helps those who are facing Page not found error.

Thanks

Harish

DotNetGuts said...

Thanks Harish for sharing your problem and solution with everyone.

Imranonline said...

Hello Friends i have problem with URL rewrite using querystring

I have a page
http://www.abc.com/details.aspx?no=123&companyname=monster&state=mumbai


select * from ms_survey_corporate where no="& request.querystring("no") &" and companyname like '%"& request.querystring("company") &"%' and state like '%"& request.querystring("state") &"%'


i use a rule as



so according to it my new friendly url is

http://www.abc.com/123/monster/mumbai.aspx


but what if i want to pass null in my querystring
like
how can i use this url without state as querystring

http://www.abc.com/details.aspx?no=123&companyname=monster

or
without state and company as querystring
http://www.abc.com/details.aspx?no=123


Kindly help me with the Rules and Process of conversion

Thanks

Unknown said...

Hi, Thanks for a great tool, I had this up and running within a matter of minutes but I have a small issue with which I may be missing an obvious point?

I have a two pages running in root:

ShowMeTowns.aspx?town=1
ShowMeVenues.aspx?venue=1

I want to display the link for ShowMeTowns.aspx as
www.mydomain.com/Abingdon.aspx
www.mydomain.com/Aldershot.aspx
www.mydomain.com/Andover.aspx

etc etc instead of
www.mydomain.com/ShowMeTowns.aspx?town=1

so I followed your insructions along with an entry into the web.config:
rewrite url="~/(.+)-(.+).aspx" to="~/ShowMeTowns.aspx?town=$2"/

which of course worked perfectly. But now I want to set up ShowMeVenues.aspx in the same way so I repeated the instructions and included another entry to the web.config:
rewrite url="~/(.+)-(.+).aspx" to="~/ShowMeVenues.aspx?venue=$2"/

but when I run this it seems because they are both running in the root there is nothing to decifer which page it needs to redirect so the urls do change but in both instances the redirect goes to ShowMeTowns.aspx as this is the first one it comes to in the web.config. Can you tell me what the key is to seperate them. Do I need two different rules in the web.config, if so what format would they be?
Thanks for any help in advance and apologies if I am missing the obvious!

DotNetGuts said...

@Damo

Its a good question.

When you use same expression twice, Url rewriter get confused and it picks one of them. (In mycase always 1st one).

Try following Solution

<rewrite url="~/venues/(.+).aspx" to="~/ShowMeVenues.aspx?venue=$1"/>

<rewrite url="~/towns/(.+).aspx" to="~/ShowMeTowns.aspx?town=$1"/>

Unknown said...

Thanks for the reply. I had already tried your solution which worked well but I needed one of the urls to be dynamic and one to be static so after alot of tweaking I came up with this as my best solution:

rewrite url="~/venuessin/(.*)-(.*).aspx" to="~/showmetowns.aspx?town=$2"/
rewrite url="~/(.+)/(.+)-(.+).aspx" to="~/showmevenues.aspx?venue=$3"/

with a global function:

Shared Function GenerateURL(ByVal DirectoryName As String, ByVal Title As String, ByVal strId As String) As String

THE REST OF THE FUNCTION AS NORMAL

'Append ID at the end of SEO Friendly URL
Select Case DirectoryName
Case "venuesin"
strTitle = "~/venuesin/" + strTitle + "-" + strId + ".aspx"
Case Else
strTitle = "~/" & DirectoryName & "/" + strTitle + "-" + strId + ".aspx"
End Select

'strTitle = "~/" & DirectoryName & "/" + strTitle + "-" + strId + ".aspx"

Return strTitle



And a call either as follows:
asp:HyperLink ID="HyperLink1" ForeColor="black" runat="server" NavigateUrl=' %# MyPubFunc.GenerateURL(DataBinder.Eval(Container.DataItem,"townname"), DataBinder.Eval(Container.DataItem,"venuename"),DataBinder.Eval(Container.DataItem,"slnid"))% ' Goto Venue /asp:HyperLink

Or:

asp:HyperLink ID="HyperLink1" ForeColor="black" runat="server" NavigateUrl=' %# MyPubFunc.GenerateURL("venuesin", DataBinder.Eval(Container.DataItem,"Description"),DataBinder.Eval(Container.DataItem,"SQGId"))% ' %# Eval("Description") % /asp:HyperLink

This way it will either allow me to pass in the venue town so it would appear in the url as:

www.mydomain.com/townname/venuename.aspx

or I can pass in a fixed extension such as 'venuesin' so my url would appear as:

www.mydomain.com/venuesin/townname.aspx

This way I can show a list of towns and click through to venues in that town and list the selected town in the url and then from there, click on a town to click through to a venue which would then have the town and the venue name in the url.

I hope this makes sense!

This is a great solution for me and hopefully it will help someone else out, so thanks again for all your help with getting to where I wanted to be, im very happy with the solution I have!

Unknown said...

Hello,

Great article, however I just wanted to know if it is possible to strip off the Title Id from the url after it has been rewritten. so something like /Article/Asp-Net-website-paths.aspx instead of /Articles/Asp-Net-website-paths-1.aspx. Now I do realize that the title id is important inorder to get the title name but just wondering if there is anything that i can do to remove the number from the generated url.

Thanks,
Wasim

Me said...

Hello,
it's really amazing work but when i used it with a project [.Net framework 4.0]
it's worked very fine but when i used it with a project [.Net framework 2.0] i got this error [Failed to map the path '/Rewritable%20url/Default3.aspx/].
Please help me ASAP
thank you...

Anonymous said...

hello i ve just rename my solution and project names(18 projects inside) but the problem with intellengcia , it get s me error(page not fund 404 error) while its is working in original website.all web.config configuration for rewriting are same as original website but it si not working in renamed new website.i ve referenced to dll etc set configuration but still getting 404 error on all rewritten url, what could be the problem.

Madhu B said...

Hi,

Very helpful article.Thank you so much. Appreciated your great efforts on GenerateURL function; you makes my job easier.

Keep going....

Waqas Memon said...

Hi i am Waqas From Karachi,Pakistan
very thanks yar Deadly solution keep it up dear. good work

kareem gamal said...

hi
thanks for this solution it worked with me fine but with one rewrite value but when I tried to use two values as:







the first value only worked but the second didn't redirect to model.aspx page.

Rishi Sanuj said...

Hi, I am implementing this rule in two page and in web config I change according to this but it always goes to first page. like I have two page 1. pressrelease.aspx and 2. solution.aspx
from press release it working fine but from solution pages it again redirect to press release landing page

kelly_seo said...

hi,
i cant find the binary file to download.
The link directs be to the source code....?

Unknown said...

hello sir i used this code in my localhost site but created url not redirect to orignal page

Unknown said...

I am getting NullReferenceException while accessing rewritten link

Unknown said...

how to Remove .aspx from page through this url rewriting

Unknown said...

how to remove .aspx through this URL Rewriting

sam said...

[InvalidOperationException: Failed to map the path '/Copy%20(2)%20of%20Rentingavenue/index.aspx/'.]
System.Web.Hosting.HostingEnvironment.MapPathActual(VirtualPath virtualPath, Boolean permitNull) +8848666
System.Web.Hosting.HostingEnvironment.MapPathInternal(VirtualPath virtualPath) +42
System.Web.VirtualPath.MapPathInternal() +4
System.Web.HttpRequest.MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, Boolean allowCrossAppMapping) +107
System.Web.HttpRequest.MapPath(VirtualPath virtualPath) +37
System.Web.HttpServerUtility.MapPath(String path) +99
Intelligencia.UrlRewriter.Utilities.HttpContextFacade.InternalMapPath(String url) +59
Intelligencia.UrlRewriter.RewriterEngine.HandleDefaultDocument(RewriteContext context) +378
Intelligencia.UrlRewriter.RewriterEngine.Rewrite() +956
Intelligencia.UrlRewriter.RewriterHttpModule.BeginRequest(Object sender, EventArgs e) +108
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75




Can any one help me out

DotNetGuts said...

@Sam, This is old way of URL Rewriting in asp.net. It is back in VS.Net 2005/2008 days. If you are using VS.Net 2010 or above then I would recommend using new way of doing URL Routing.

Check out this url for more info.
http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx

sam said...

@DotNetGuts, Thanks for replying...
I went through the link and found it useful but i am still using 2.0 so it would be better if i use the above mentioned code. So can you please help me sorting out the problem.

DotNetGuts said...

@Sam,

It is hard to help you out with just error message. There can be many reasons by which above exception can be thrown. Please go through comments answered above. Hope that helps.

Unknown said...

Thanks Sir,
its a nice article..
but its giving error " Could not load file or assembly 'Intelligencia.UrlRewriter' or one of its dependencies. The system cannot find the file specified"
Plz help me..

DotNetGuts said...

@Sumit,

This article is very old. If you have to do URL Rewriting in Asp.net 4.0 or Up, I would suggest you too look into routing engine, that is much more efficient than this.

Your error clearly states answer: check whether dll file is not corrupt and properly reference.

Naat Khan said...

nice it is working fine......

but how to use multiple url inside



Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape