简体   繁体   中英

ASP.NET URL Rewriting for query strings

For a more user-friendly environment, I wish to have the page extensions removed and query strings to not be visible. For example, from http://www.example.com/news.aspx?id=123 I want it to be http://www.example.com/news/123 . How can I obtain it?

I also wanted to take opportunity of this question to put two other questions:

  • When using the URL rewriting, do I have to specify a rule for each page?
  • Which is better to use for URL rewriting in ASP.NET - the .htaccess file or the setting of rules in the web.config ?

Thanks.

You can use the URL Routing classes that were introduced in ASP.Net MVC for this purpose. These classes can be used in any .Net web application and are not limited to the MVC release.

With the "System.Web.Routing" namespace in place you can define routes as rules such as;

routes.MapPageRoute(
      "News Category",   // Route name
      "News/{*ID}",      // Route URL
      "~/News.aspx"      // Web page to handle route
   );

You register these "routes" in your global.asax application startup event in the same manners as you would in MVC.

This would allow http://www.domain.com/news/123 to be interpreted in your web application in the same manner as http://www.domain.com/news.aspx?id=123 .

Here's a recent article on using the MVC routing namespace in a traditional aspx application.

  • When using the URL rewriting, do I have to specify a rule for each
    page?

No most URL Rewriting mechanisms allow for regular expressions to be used to combine URL's to use one specific rule.

  • Which is better to use for URL rewriting in ASP.NET - the
    .htaccess file or the setting of rules in the web.config?

When using IIS 7 or up, you can use the IIS URL Rewrite module, see http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/

When using IIS 6 or lower I prefer the URL Rewriting module from: http://www.urlrewriting.net/ but there are others you can use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM