DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

URL Rewrite in Asp.net Web Forms

In ASP.NET Web Forms, you can use URL rewriting techniques to change the appearance of your website's URLs. URL rewriting allows you to present user-friendly and search engine-friendly URLs that are more meaningful and descriptive.

Here's how you can perform URL rewriting in ASP.NET Web Forms:

  1. Enable URL rewriting: In your web.config file, make sure the <system.webServer> section includes the following configuration to enable URL rewriting using the IIS Rewrite module:
<system.webServer>
  <rewrite>
    <rules>
      <rule name="Rewrite to friendly URL">
        <match url="^([a-zA-Z0-9]+)/?$" /> <!-- Regular expression to match the friendly URL pattern -->
        <action type="Rewrite" url="Page.aspx?id={R:1}" /> <!-- Rewrite the URL to the desired format -->
      </rule>
    </rules>
  </rewrite>
</system.webServer>
Enter fullscreen mode Exit fullscreen mode
  1. Define the URL rewriting logic: In your ASP.NET Web Forms code-behind or in a separate class, handle the rewritten URL and extract the necessary information to determine which page or content to display. You can access the rewritten URL parameters using Request.QueryString.
protected void Page_Load(object sender, EventArgs e)
{
    string id = Request.QueryString["id"];
    // Use the extracted ID to retrieve the relevant content and populate the page
}
Enter fullscreen mode Exit fullscreen mode
  1. Generate and link to the friendly URLs: When generating links within your application, use the desired friendly URL format instead of the actual page name or query string parameter. For example:
<a href="Products/123">View Product</a>
Enter fullscreen mode Exit fullscreen mode
  1. Handle the rewritten URL on the server: In the Page_Load event or another appropriate event handler, parse the rewritten URL and process it accordingly to display the correct content on the page.

It's worth noting that URL rewriting can be more complex depending on your specific requirements. You may need to adjust the regular expression pattern and the logic to handle different URL structures or route to different pages. Additionally, you can also consider using a URL rewriting library or framework, such as ASP.NET Routing or third-party solutions, to simplify the implementation and provide more advanced routing capabilities.

Remember to test your URL rewriting implementation thoroughly to ensure that the rewritten URLs work as expected and that they don't introduce any issues with your application's functionality.

Top comments (0)