Garrett
Garrett

Reputation: 1688

URL Rewriting in .NET 4

What is the best solution to URL Rewriting in .NET 4. I'm looking for an easy solution to rewrite URLs like

"myurl.com/ApplicationName/Kohls" to something like "myurl.com/ApplicationName/index.html?store=Kohls" so I can access the var "Kohls" through the Query String.

I am currently using the Global.asax and it has been working for the above case - but I am running into trouble in the case where the user would enter myurl.com/Application, with no "/" or anything after Application.

I currently have this:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        String CurrentURLPath = Request.Path.ToUpper();

        Match nothingAfterRoot = Regex.Match(CurrentURLPath, @"/ApplicationName(/)?$", RegexOptions.IgnoreCase);
        if (nothingAfterRoot.Success)
        {
            HttpContext myContext = HttpContext.Current;
            myContext.RewritePath("/ApplicationName/Default.aspx?store=ABC");
        }
        else
        {
            Match match = Regex.Match(CurrentURLPath, @"/ApplicationName(/)?(\w)*$", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                CurrentURLPath = CurrentURLPath.Trim('/');
                String store= CurrentURLPath.Split("ApplicationName/".ToCharArray())[1];
                HttpContext myContext = HttpContext.Current;
                myContext.RewritePath(String.Format("/ApplicationName/Default.aspx?store={0}", store));
            }
        }
    }

Upvotes: 0

Views: 2741

Answers (3)

John Bonfardeci
John Bonfardeci

Reputation: 476

What is the best solution to URL Rewriting in .NET 4

Use MVC framework if you have the option. The URL rewriting is the default.

For traditional asp.net sites, I use the UrlRewritingNet.UrlRewriter.dll with the following to my web.config file:

<configSections>
    <section name="urlrewritingnet" restartOnExternalChanges="true" 
        requirePermission="false" type="UrlRewritingNet.Configuration.UrlRewriteSection, 
        UrlRewritingNet.UrlRewriter" />
</configSections>

<system.web>
    <urlrewritingnet rewriteOnlyVirtualUrls="true" contextItemsPrefix="QueryString" 
         defaultPage="default.aspx" defaultProvider="RegEx"       
         xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
        <rewrites>
          <add name="ArticleUrlRewrite" virtualUrl="^~/a-(.*)-([\w-]*)\.aspx" 
               rewriteUrlParameter="ExcludeFromClientQueryString" 
               destinationUrl="~/article.aspx?id=$1" ignoreCase="true" />
        </rewrites>
    </urlrewritingnet>
</system.web>

Upvotes: 2

Jonathan
Jonathan

Reputation: 5028

As mentioned above, MVC is a good approach, if it's an option.

If you're running IIS 7, there's a URL Rewrite module available:

http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/ and http://www.microsoft.com/en-us/download/details.aspx?id=7435

If you're running IIS6, you can use urlrewritingnet as mentioned above or, as I prefer, IIRF:

http://iirf.codeplex.com/

The mod-rewrite similarities and regex-based rules make it very powerful

Upvotes: 0

feco
feco

Reputation: 4423

You can use ShortURL-dotnet to rewrite a URL like bit.ly/XXXX to www.mysite.com/index.htm

It changes the default error page to the redirection file, and depending if the value exists, it will redirect you to the real URL.

If you are interested in this solution you can find more at http://sourceforge.net/projects/shorturl-dotnet/

using System;
using System.Web;

public partial class Redirection : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ShortUrl.Container oShortUrl;

        if (ShortUrl.Utils.HasValue(Request.QueryString["page"].ToString())) // checks in case ISAPIRewrite is being used
        {
            oShortUrl = ShortUrl.Utils.RetrieveUrlFromDatabase(Request.QueryString["page"].ToString());
        }
        else // using IIS Custom Errors
        {
            oShortUrl = ShortUrl.Utils.RetrieveUrlFromDatabase(ShortUrl.Utils.InternalShortUrl(Request.Url.ToString()));
        }

        if (oShortUrl.RealUrl != null)
        {
            Response.Redirect(oShortUrl.RealUrl);
        }
        else
        {
            Response.Redirect("MissingUrl.aspx");
        }
    }
}

Upvotes: 1

Related Questions