Thursday, February 10, 2011

ASP.NET URL redirection

I want, when I type http://localhost/Admin, to take me to the page http://localhost/Something/Login.aspx. How can I do this?

  • What you are looking for is called Forms Authentication. A very short introduction follows.

    You need to create a login page that makes a call like this, after verifying the identity of the user:

    FormsAuthentication.RedirectFromLoginPage(userName);
    

    Then you need to wire up the login page in the web.config file:

    <system.web>
      <authentication mode="Forms">
        <forms loginUrl="~/Something/Login.aspx" />
      </authentication>
    </system.web>
    

    Furthermore, you will need to tell the framework that all URLs below ~/Admin/ requires the user to be authenticaticated. This can be done by adding an another web.config file within that folder:

    <system.web>
      <authorization>
        <deny users="?" />
        <allow users="*" />
      </authorization>
    </system.web>
    

    Read the article linked above, or search the web for "ASP.NET forms authentication" and you will soon be on the right track.


    EDIT 1 - If all you want to do is really to "make a redirect to a specific URL", then this is sufficient:

    Response.Redirect("~/Something/Login.aspx")
    

    From the URLs you mention in the your questions, it seems that you are trying to enforce some kind of authentication/authorization scheme. If this is true, forms authentication is a better answer.


    EDIT 2 - If you want to rewrite, not redirect, requests from ~/Admin to ~/Something/Login.aspx you can do so by mapping a URL mapping in your root web.config file

    <system.web>
        <urlMappings>
            <add url="~/Admin/Default.aspx" mappedUrl="~/Something/Login.aspx"/>
        </urlMappings>
    </system.web>
    

    In most setups, the web server will only pass the request to ASP.NET if the requested URL ends with a known suffix, such as .aspx. On approach to trick the web server to pass requests for ~/Admin to ASP.NET, is to use the "default document" feature in the web server. For this to work, you must add an empty file named Default.aspx in the ~/Admin folder.

  • If you want to know about URL rewriting in .NET (and aren't using ASP.NET MVC or Routing which is new in .NET 3.5 SP1) then this blog has an excellent explanation on using the UrlRewriter.Net component... although your question does tend to lead to Jørn's response.

    From Kane
  • You should read this:

    http://msdn.microsoft.com/en-us/library/ms972974.aspx

0 comments:

Post a Comment