Introduction

Websites often need to generate SEO friendly URLs. In ASP.NET Web Forms applications, a URL is tied to a physical .aspx file. This default mapping between a URL and physical file makes it difficult for Web Forms applications to generate SEO friendly URLs. One option available to ASP.NET developers is to use URL routing features. Alternatively they can also use Friendly Urls - a feature that allows you to quickly and easily use SEO friendly URLs in Web Forms applications. This article discusses how.

Overview of Friendly URLs

Suppose that you are developing a blog engine that has a web form, say WebForm1.aspx, for displaying a blog post. Traditionally developers passed blog post ID in the querystring of WebForm1.aspx so that different blog posts corresponding to the post ID passed can be displayed. In this arrangement the URLs for different blog posts will look like this:

  1. http://somewebsite/WebForm1.aspx?postid=1
  2. http://somewebsite/WebForm1.aspx?postid=2
  3. http://somewebsite/WebForm1.aspx?postid=3
Inside the #1 Cloud Platform for Building Next-Gen Apps
 
 

Such URLs are obviously not SEO friendly URLs. Wouldn't it be nice if you could generate friendly URLs in the following format?

  1. http://www.somewebsite/WebForm1/2013/03/10/1234

As you can see from the above URL, the WebForm1 is used without any file extension. Additionally, blog post information such as year, month and day of publication is appended to the main URL along with the post ID. This way each blog post gets a unique URL without using any querystring parameters. Such URLs can be easily generated using ASP.NET FriendlyUrls. Moreover, it takes just a few lines of code to generate these URLs.

Installing Friendly Url via NuGet

In order to use ASP.NET FriendlyUrls you need to install the required assemblies using a NuGet package. So, open Visual Studio 2012 and create a blank ASP.NET Web Forms application. Then click on the Project > Manage NuGet Packages menu option. In the resulting dialog search for FriendlyUrls. You should see the Microsoft ASP.NET Friendly URLs entry listed as shown in the following figure.

Microsoft ASP.NET Friendly URLs

Once you install the necessary NuGet package you will find that a reference is added to the Microsoft.AspNet.FriendlyUrls assembly. Now you are ready to use FriendlyUrls in your application.

Enabling Friendly Urls

Next, open Global.asax file in Visual Studio and write the following code in its Application_Start event handler.

  1. protected void Application_Start(object sender, EventArgs e)
  2. {
  3. RouteTable.Routes.EnableFriendlyUrls();
  4. }

The above code calls the EnableFriendlyUrls() method on the Routes collection. Calling the EnableFriendlyUrls() method enables FriendlyUrls for your application and you can use all the Web Form URLs without the .aspx extension. For example, instead of accessing a web form as /samplewebsite/WebForm1.aspx you can simply say /samplewebsite/WebForm1

Remember that EnableFriendlyUrls() is an extension method and you must import the following namespaces at the top of Global.asax.

  1. using System.Web.Routing;
  2. using Microsoft.AspNet.FriendlyUrls;

Getting Information about FriendlyUrls

Inside the Web Form you may want to know the path information about a FriendlyUrl. You can easily obtain that information as shown below:

  1. string path = Request.GetFriendlyUrlFileVirtualPath();
  2. string ext = Request.GetFriendlyUrlFileExtension();
  3. string friendlyurl = FriendlyUrl.Resolve("~/WebForm2.aspx");
  4. string link = FriendlyUrl.Href("~/WebForm1", 2013, 03, 10, 1234);

As you can see from the above code, several extension methods get added to the Request object. The GetFriendlyUrlFileVirtualPath() method returns the virtual path corresponding to the FriendlyUrl being accessed. For example, for a friendly URL http://somewebsite/WebForm1 it will return ~/WebForm1.aspx

The GetFriendlyUrlFileExtension() method returns the physical file extension of a FriendlyUrl. For web form files, it will be .aspx.

You can also generate FriendlyUrls via code using the Resolve() method of the FriendlyUrl class. The Resolve() method accepts a virtual path and resolves that path to the corresponding FriendlyUrl.

The Href() method of the FriendlyUrl class can be used to generate hyperlink URLs. It accepts the virtual path of the FriendlyUrl followed by URL segments (more on that later). For example, if you wish to generate a hyperlink that points to /somewebsite/WebForm1/2013/03/10/1234 then the first parameter will be ~/WebForm1 and URL segments will be 2013, 03,10 and 1234.

Accessing URL Segments in Code

FriendlyUrls features are not limited to generating extensionless URLs. You can also pass data to the underlying Web Form through URL segments. In the blog engine example we discussed earlier, the year, month and day of publication is passed to the Web Form along with the post ID. These pieces of information are passed as URL segments as shown below:

  1. http://www.somewebsite/WebForm1/2013/03/10/1234

The URL segments that you pass along with a FriendlyUrl can be retrieved inside the Web Form code-behind file as shown below:

  1. IList<string> segments = Request.GetFriendlyUrlSegments();
  2. BlogPost post = new BlogPost();
  3. post.Year = int.Parse(segments[0]);
  4. post.Month = int.Parse(segments[1]);
  5. post.Day = int.Parse(segments[2]);
  6. post.PostId = int.Parse(segments[3]);

As you can see, the code-behind uses the GetFriendlyUrlSegments() extension method on the Request object. The GetFriendlyUrlSegments() returns an IList of string. Once retrieved you can access and parse the individual segment and assign to a class named BlogPost. The BlogPost class is a simple class with four public properties, viz. Year, Month, Day and PostId.

  1. public class BlogPost
  2. {
  3. public int Year { get; set; }
  4. public int Month { get; set; }
  5. public int Day { get; set; }
  6. public int PostId { get; set; }
  7. }

FriendlyUrls and ValueProviders

It is also easy to use FriendlyUrls with data bound controls such as GridView and FormView. Consider, for example, that the Web Form that displays a blog post houses a FormView control to do so. The FormView control can use SelectMethod and ItemType properties to specify a method returning the data to be bound and type of the data being returned respectively.

  1. <asp:FormView ID="FormView1" runat="server" ItemType="FriendlyUrlsDemo.BlogPost" SelectMethod="GetBlogPost">
  2. <ItemTemplate>
  3. ...
  4. </ItemTemplate>
  5. </asp:FormView>

As you can, see the ItemType property points to the BlogPost class you created earlier and the SelectMethod property points to a public method named GetBlogPost(). The GetBlogPost() method is shown below:

  1. public BlogPost GetBlogPost([FriendlyUrlSegments(0)]int year,
  2. [FriendlyUrlSegments(1)]int month,
  3. [FriendlyUrlSegments(2)]int day,
  4. [FriendlyUrlSegments(3)]int postid)
  5. {
  6. //you may add some custom processing here
  7. BlogPost post = new BlogPost();
  8. post.Year = year;
  9. post.Month = month;
  10. post.Day = day;
  11. post.PostId = postid;
  12. return post;
  13. }

As you can see the GetBlogPost() method has four parameters, viz. year, month, day and postid. These parameter values will be passed through the URL segments as discussed earlier. You need to map the URL segments with the appropriate method parameters. You can do this using the [FriendlyUrlSegments] attribute. The [FriendlyUrlSegments] attribute is a value provider and is applied to various parameters of the GetBlogPost() method. It takes an index of the URL segment you wish to bind with a method parameter. In the above example, if you have URL like this:

  1. http://www.somewebsite/WebForm1/2013/03/10/1234

Then year, month, day and postid parameters will be 2013, 03,10 and 1234 respectively. Although the above example simply constructs a BlogPost object based on the URL segment values you can add any custom processing here.

Summary

FriendlyUrls allow you to generate SEO friendly URLs quickly and easily. In order to use FriendlyUrls you need to add Microsoft ASP.NET FriendlyUrls NuGet package to your project. Once added you can enable extensionless URLs for your Web Forms by enabling the FriendlyUrls feature in the Global.asax. You can also access URL segments and even bind them to method parameters.

一个令人蛋疼的 Microsoft.AspNet.FriendlyUrls

 

我一个项目都基本上做完了,结果部署到我服务器的时候结果一直报404 找不到 一看global.asax有个路由注册的代码

1
2
3
4
public static void RegisterRoutes(RouteCollection routes)
      {
          routes.EnableFriendlyUrls();
      }

放在IIS中 始终是找不到类似伪静态的地址

如:localhost/default这种

找了两天 我还把多个IIS里面的模块都一一比对 还是不对,最后在老外的一篇文章中终于解决了这个问题

http://weblog.west-wind.com/posts/2011/Mar/27/ASPNET-Routing-not-working-on-IIS-70

在web.config 添加

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">     
    </modules>
  </system.webServer>

搞定。。。。。。。。。。。。。。。

如果不加上面的话IIS会用自己的解析方式去解析 所以一直解析不到

记在这里以备后用

Using Friendly URLs in ASP.NET Web Forms的更多相关文章

  1. [转]Bootstrap 3.0.0 with ASP.NET Web Forms – Step by Step – Without NuGet Package

    本文转自:http://www.mytecbits.com/microsoft/dot-net/bootstrap-3-0-0-with-asp-net-web-forms In my earlier ...

  2. 【翻译】使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定

    原文地址:http://www.dotnetjalps.com/2013/05/Simple-data-binding-with-Knockout-Web-API-and-ASP-Net-Web-Fo ...

  3. Asp.Net学习进度备忘(第一步:ASP.NET Web Forms)

    书签:“Web Pages”和“MVC”跳过:另外跳过的内容有待跟进 __________________ 学习资源:W3School. _________________ 跳过的内容: 1.ASP. ...

  4. ASP.NET Web Forms的改进

    虽然ASP.NET Web Forms不是vNext计划的一部分,但它并没有被忽视.作为Visual Studio 2013 Update 2的一部分,它重新开始支持新工具.EF集成和Roslyn. ...

  5. ASP.NET Web Forms 4.5的新特性

    作者:Parry出处:http://www.cnblogs.com/parry/ 一.强类型数据控件 在出现强类型数据控件前,我们绑定数据控件时,前台一般使用Eval或者DataBinder.Eval ...

  6. Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定

    使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定   原文地址:http://www.dotnetjalps.com/2013/05/Simple-da ...

  7. ASP.NET Web Forms - 网站导航(Sitemap 文件)

    [参考]ASP.NET Web Forms - 导航 ASP.NET 带有内建的导航控件. 网站导航 维护大型网站的菜单是困难而且费时的. 在 ASP.NET 中,菜单可存储在文件中,这样易于维护.文 ...

  8. 在ASP.NET Web Forms中用System.Web.Optimization取代SquishIt

    将一个ASP.NET Web Forms项目从.NET Framework 4.0升级至.NET Framework 4.5之后,发现SquishIt竟然引发了HTTP Error 500.0 - I ...

  9. ASP.NET Web Forms 的 DI 應用範例

    跟 ASP.NET MVC 与 Web API 比起来,在 Web Forms 应用程式中使用 Dependency Injection 要来的麻烦些.这里用一个范例来说明如何注入相依物件至 Web ...

随机推荐

  1. VS 2013 未找到与约束contractname Microsoft.VisualStudio.Utilities.IContentTypeRegistryService...匹配的导出[vs故障]【转】

    未找到与约束 contractname Microsoft.VisualStudio.Utilities.IContentTypeRegistryService RequiredTypeIdentit ...

  2. Apache Shiro和Spring Security的详细对比

    参考资料: 1)Apache Shiro Apache Shiro:http://shiro.apache.org/ 在Web项目中应用 Apache Shiro:http://www.ibm.com ...

  3. 通过自定义Attribute及泛型extension封装数据验证过程

    需求来源: 在日常工作中,业务流程往往就是大量持续的数据流转.加工.展现过程,在这个过程中,不可避免的就是数据验证的工作.数据验证工作是个很枯燥的重复劳动,没有什么技术含量,需要的就是对业务流程的准确 ...

  4. poi-处理excel的单元格日期数据

    poi处理excel时,当excel没有明确指明是哪个类型的数据时,poi很可能处理单元格的日期数据时就有可能是一串数字.而使用java程序基本无法转换 以下为对poi处理日期情况一些方面的处理(不是 ...

  5. vim——打开多个文件、同时显示多个文件、在文件之间切换

    打开多个文件: 1.vim还没有启动的时候: 在终端里输入  vim file1 file2 ... filen便可以打开所有想要打开的文件 2.vim已经启动 输入 :open file 可以再打开 ...

  6. ARP协议工作流程

    地址解析协议,即ARP(Address Resolution Protocol),是根据IP地址获取物理地址的一个TCP/IP协议.主机发送信息时将包含目标IP地址的ARP请求广播到网络上的所有主机, ...

  7. 【poj2459】 Feed Accounting

    http://poj.org/problem?id=2459 (题目链接) 题意 一堆不知何时运到的草料原有F1 kg,在第D天被牛吃成F2 kg,每头牛在[l,r]吃草料,每天吃1kg.求草料是什么 ...

  8. QTVA-2015-198545、WooYun-2015-104148 .NET Framework Arbitrary File Permissions Modify Vul

    catalog . Description . Effected Scope . Exploit Analysis . Principle Of Vulnerability . Patch Fix 1 ...

  9. MongoDB: 数据库复制

    db.copyDatabase("from","to","127.0.0.1:16161"); 将127.0.0.1上的from库.拷贝到t ...

  10. vi命令大全

    参考 http://www.cnblogs.com/88999660/articles/1581524.html 最近要用到linux和shell脚本,所以多学习下,反正没什么坏处 在linux里面, ...