URL Rewriting в ASP.NET

URL Rewriting в ASP.NET

by Адель Шигабутдинов 3. ноября 2007 01:51

URL Rewriting. Что это и зачем?

Основные цели для использования URL Rewriting две:
1. Обеспечить лучшую индексацию в поисковых машинах. URL Rewriting позволяет включать основные слова прямо в URL, да и вообще, прямые ссылки приносят большие баллы в поисковых системах.
2. Сделать пути к статьям независимыми от структуры сайта (чтобы в случае изменения структуры вашего сайта, ссылки из «избранного» оставались «живыми»).
3. Сделать пути легкозапоминаемыми для людей.

Ну, вот пример. Мы пишем сайт какого-то журнала, и страницы в нем организованы по категориям (about, press, people, subscribe).
У нас есть страница “Show.aspx”, которая берет название категории из Querystring и делает выборку из базы. Запросы к странице Show.aspx сейчас выглядят так:

http://www.journal.ru/show.aspx?show=about
http://www.journal.ru/show.aspx?show=press
http://www.journal.ru/show.aspx?show=people
http://www.journal.ru/show.aspx?show=subscribe

Нас это не устраивает, и мы хотим изменить приложение так, чтобы адрес каждой страницы выглядел уникальным для поисковых машин.
Используем HttpModule для URL Rewriting
Вот как будут выглядеть наши пути после перезаписи:

http://www.journal.ru/About.aspx
http://www.hournal.ru/Press.aspx
http://www.hournal.ru/People.aspx
http://www.hournal.ru/Subscribe.aspx

Всё это безобразие выглядит как 4 разных страницы на сайте (и очень радует поисковые сервера!), но на самом деле, это ссылки на Show.aspx. Используя метод HttpContext.RewritePath(), мы можем динамически переписывать входящие URL чтобы они обращались к Show.aspx, которая принимает аргументы из Querystring. Для этого, можно использовать событие в Global.asax: 

 void Application_BeginRequest(object sender, EventArgs e) {

        string fullOrigionalpath = Request.Url.ToString();
       
        if (fullOrigionalpath.Contains("/About.aspx")) {
            Context.RewritePath("/Show.aspx?show=about");
        }
        else if (fullOrigionalpath.Contains("/Press.aspx")) {
            Context.RewritePath("/Show.aspx?show=press");
        }
    } 

Минусы этого способа: обычно бывает лень это писать, да легко можно запутаться и сделать ошибки. За вас уже все придумано и написано, можно просто воспользоваться одним из готовых компонентов:

Эти модули позволяют прописать вам в web.config правила перезаписи адресов. Например, используя UrlRewriter.Net, нужно записать в web.config привязку четырех URL к файлу Show.aspx:

<?xml version="1.0"?>

<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>

  <rewriter>
    <rewrite url="~/About.aspx" to="~/show.aspx?show=about" />
    <rewrite url="~/Press.aspx" to="~/show.aspx?show=press" />
    <rewrite url="~/People.aspx" to="~/show.aspx?show=people" />
    <rewrite url="~/Subscribe.aspx" to="~/show.aspx?show=subscribe" />
  </rewriter> 
 
</configuration> 

HttpModule URL Rewriter-ы еще позволяют воспользоваться регулярными выражениями, чтобы не  заставлять разработчика добавлять в web.config вообще все динамические ссылки! ))) По-этому можно переписать правила немного иначе, так, чтобы любой адрес /[category-name].aspx работал через Show.aspx: 

  <rewriter>
    <rewrite url="~/(.+).aspx" to="~/show.aspx?show=$1" />
  </rewriter>  

Это делает наш код очень гибким. Я думаю не нужно объяснять, для чего это нужно. Все очень легко и просто, а главное, никакого лишнего гемора.
Этот способ я использовал на www.kazved.ru, можете посмотреть, как это работает там.
В Apache+PHP для этого используется mod_rewrite.

Комментарии

10.03.2008 21:33:03 #

3dmax

Приветствую! Сейчас изучаю библиотеку  UrlRewritingNet.. все отлично, вот только у меня возник такой вопрос, можно ли с помощью этогй библиотеки преобразовавать ссылки в коде на стадии построения страницы?
Не хочу сильно менять существующий код, куда лучше написать несколько регулярных выражений и преобразовывать уже готовые ссылки при помощи одного метода.

3dmax

11.03.2008 2:00:31 #

DrFaust

Честноговоря в работу этого компонента не вникал, когда мне было нужно, просто поменял в коде генерацию ссылок с "page.aspx?id="+int на "/page/"+int+".aspx" Smile

DrFaust

11.03.2008 13:20:43 #

3dmax

Smile уже разобрался Smile).. у меня не получалось из-за того, что не совсем корректно унаследовал класс от RewritingRole. Все оказалось очень просто.(как и всегда.. порой так лень думать Smile)) )

3dmax

19.07.2010 19:04:59 #

wow gold

Hi I found your site by mistake when i was searching Google for this registry cleaner issue, I must say your site is really helpful I also love the design, its amazing!. I don't have the time at the moment to fully read your sitebut I have bookmarked it and also add your RSS feeds. I will be back in a day or two. thanks for this site.

wow gold

19.07.2010 19:38:34 #

youku love

Hey very nice blog!!  .. I will bookmark your blog and take the feeds also...

youku love

19.07.2010 20:12:05 #

WoW Gold Cheat

Pingback from 375.dlmreza.netAuto Parts Volvo 242 Fuel Pump, 242 Cheap Ed Hardy Hollister

WoW Gold Cheat

22.07.2010 8:29:01 #

wow gold

Without doubt agree with what you said. Your explanation was undoubtedly the simplest to understand. I tell you, I often get annoyed when folks explain things that they plainly don't know about. You managed to hit the nail right on the head and also explained out everything clearly. Maybe, others can take a cue. Will likely be back for additional. Thanks

wow gold

22.07.2010 8:56:32 #

2010 game

This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!

2010 game

22.07.2010 9:25:57 #

Wow Gold Online

This is getting a bit more subjective, but I much prefer the Zune Marketplace. The interface is colorful, has more flair, and some cool features like 'Mixview' that let you quickly see related albums, songs, or other users related to what you're listening to. Clicking on one of those will center on that item, and another set of &quot;neighbors&quot; will come into view, allowing you to navigate around exploring by similar artists, songs, or users. Speaking of users, the Zune &quot;Social&quot; is also great fun, letting you find others with shared tastes and becoming friends with them. You then can listen to a playlist created based on an amalgamation of what all your friends are listening to, which is also enjoyable. Those concerned with privacy will be relieved to know you can prevent the public from seeing your personal listening habits if you so choose.

Wow Gold Online

24.07.2010 23:30:05 #

wow gold

I must say, youve got one of the best blogs Ive seen in a long time.  What I wouldnt give to be able to create a blog thats as interesting as this.  I guess Ill just have to keep reading yours and hope that one day I can write on a subject with as much knowledge as youve got on this one!

wow gold

25.07.2010 1:10:53 #

aion information

Couldnt be written any better. Reading this column reminds me of my old room mate! He always kept talking about this. I'll forward this article to him. Pretty certain he will have an excellent read. Appreciation for sharing!

aion information

25.07.2010 2:29:45 #

game love

Add New Comment

game love

29.07.2010 2:52:10 #

wow gold

I Like your blog and posts.I often visit it.

wow gold

29.07.2010 3:24:15 #

life time

You...are...my...hero!!!  I cant believe something like this exists on the internet!  Its so true, so honest, and more than that you dont sound like an idiot!  Finally, someone who knows how to talk about a subject without sounding like a kid who didnt get that bike he wanted for Christmas.

life time

29.07.2010 4:07:09 #

2010 game

I just want to say I like it and thanks.I really like your style of blogging.

2010 game

02.08.2010 6:24:50 #

lenen

Over de voor- en nadelen van het afsluiten van een lening zonder BKR-toetsing.

lenen

10.08.2010 6:21:03 #

hypotheek

Hypotheek informatie, hypotheek aanvragen of afsluiten? Hypotheekrentes bekijken. Hypotheek aanbieders vergelijken, hypotheek vormen, bijkomende kosten,

hypotheek

18.08.2010 3:38:04 #

vigrx

your site layout is very good

vigrx

28.08.2010 3:46:42 #

nude chat

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

nude chat

30.08.2010 1:10:44 #

where to buy online cialis 100mg pills in West jefferson NC 28694 North Carolina

Took me time to read all of the feedback, but I actually loved the article. It proved to be very helpful to me and I am sure to all of the commenters right here! It's at all times good when you can't only learn, but additionally entertained! I'm certain you had pleasure writing this article.

where to buy online cialis 100mg pills in West jefferson NC 28694 North Carolina United States

30.08.2010 7:57:36 #

the best herbal cialis

You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog. Certainly, these practices are unfair; but they say that most of their rules are only to apply to people who overdraw.

the best herbal cialis United States

01.09.2010 9:04:36 #

quit smoking products inhaler

The gums, patches, and hard candies that contain nicotine for those who want to quit can be found in any store. They contain small amounts of nicotine so that it will help the quitting person to compensate for the sudden lack of this addictive substance as an effect of quitting. The dosage on these things can then be lessened as the days go by. Anti-depressants such as zyban, Chantrix, and other medicine can also be used to help lessen the withdrawal syndrome. If these are still not enough, you should look for other programs about kicking the habit, which many are available online.

quit smoking products inhaler

01.09.2010 18:18:23 #

ffxiv gil

Hi. I wanted to drop you a quick note to express my thanks. I've been following your blog for a month or so and have picked up a ton of good information as well as enjoyed the way you've structured your site. I am attempting to run my own blog but I think its too general and I want to focus more on smaller topics. Being all things to all people is not all that its cracked up to be.

ffxiv gil

01.09.2010 18:59:04 #

ff14 gil

Very informative post, keep up the good work.

ff14 gil

01.09.2010 19:31:12 #

ffxiv gold

I think you have to improve a bit the design and usability of your blog.

ffxiv gold

02.09.2010 7:46:01 #

Master Cleanse Lemonade Diet

This was a great post, I hope you will write some more of these in the future....

Master Cleanse Lemonade Diet

08.09.2010 7:26:42 #

financial spread betting

financial spread betting financial spread betting financial spread betting financial spread betting financial spread betting financial spread betting financial spread betting financial spread betting financial spread betting financial spread betting

financial spread betting

Добавить комментарий


(Отображает Gravatar)

biuquote
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

Об авторе блога

Адель Шигабутдинов (веб-разработчик)