Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

2009 - Basta!: Url rewriting mit iis, asp.net und routing engine

Url rewriting mit iis, asp.net und routing engine

  • Be the first to comment

  • Be the first to like this

2009 - Basta!: Url rewriting mit iis, asp.net und routing engine

  1. 1. 1 Daniel Fisher daniel.fisher@devcoach.biz
  2. 2. 2 Daniel Fisher CTO. MCP, MCTS, MCPD… Mit-Gründer und Geschäftsführer von devcoach® Mit-Gründer und Vorstand der just community e.V. Leiter der .NET-Nieder-Rhein INETA User-Group Mitglied im Microsoft Community Leader & Insider Program (CLIP) Connected Systems Advisory Board
  3. 3. 3 Projekte, Beratung & Training  REST & SOA – Architektur  BPM & FDD – Prozesse  Sicherheit & Claims – Identity  DAL & ORM – Daten  RIA & AJAX – Web 2.0 Technologien  ASP.NET, WCF, WF & CardSpace – .NET Kunden  Versicherungen, Großhandel, Software – u.A. Microsoft Project Experience Technology Know-how devcoach®
  4. 4. 4  Nice URLs  URL Rewriting  IIS Rewriting Module  Classic ASP.NET  ASP.NET Routing Engine  Solving Postback Issues
  5. 5. 5
  6. 6. 6 http://www.basta.net/View.aspx?y={7B5BBD55- 40F3-4ccb-852D-E6D0DB3D308D}& t={31646FBE-CC9C-43c8-AB77- BE149F2C2B99}&c={070877AA-668D-47d7- 872E-5838CD5E2F8B} daniel.fisher@devcoach.biz
  7. 7. 7 http://www.basta.net/2009/Speakers daniel.fisher@devcoach.biz
  8. 8. 8  Usability-Guru Jakob Neilsen recommends that URLs be chosen so that they:  Are short.  Are easy to type.  Visualize the site structure.  "Hackable," allowing the user to navigate through the site by hacking off parts of the URL. daniel.fisher@devcoach.biz
  9. 9. 9  Dynamic web pages like ASP.NET rely on parameters as non web apps do.  Web applications user GET or POST variables to transmit values.  Query strings are  Not soooooo nice  Hard to remember  Look like parameters  Internally they are but for instance looking at a categories products is not seen as an action by the user… daniel.fisher@devcoach.biz
  10. 10. 10daniel.fisher@devcoach.biz
  11. 11. 11 Operating System HTTP.SYS Internet Information Services InetInfo •Metabase W3SVC •ProcMgr •ConfMgr Application Pool – W3WP.exe WebApp •Global •Modules •Handler WebApp •Global •Modules •Handler Cache
  12. 12. 12 HTTP.SYS IIS aspnet_isa pi.dll Module HandlerModuleModuleModule
  13. 13. 13 HTTP.SYS IIS Module HandlerModuleModuleModule
  14. 14. 14daniel.fisher@devcoach.biz
  15. 15. 15  Rule based  UI (IISMGR)  ISAPI extension  Global and distributed rewrite rules  …  It's Infrastructure!
  16. 16. 16 <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="RedirectUserFriendlyURL1" stopProcessing="true"> <match url="^default.aspx$" /> <conditions> <add input="{REQUEST_METHOD}" negate="true" pattern="^POST$" /> <add input="{QUERY_STRING}" pattern="^([^=&amp;]+)=([^=&amp;]+)$" /> </conditions> <action type="Redirect" url="{C:1}/{C:2}" appendQueryString="false" redirectType="Permanent" /> </rule> <rule name="RewriteUserFriendlyURL1" stopProcessing="true"> <match url="^([^/]+)/([^/]+)/?$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="default.aspx?{R:1}={R:2}" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
  17. 17. 17 Creating a "nice" URL
  18. 18. 18  IIS URL Rewrite Module updates ASP.NET bugs  "~" is resolved incorrectly when using URL rewriting  SiteMap.CurrentNode property returns null when sitemap contains virtual URLs  Only if the machine has .NET Framework version 3.5 SP1 or higher.  If .NET is installed after URL Rewrite re-install or repair!
  19. 19. 19  IIS URL Rewrite Module  x86: http://www.microsoft.com/downloads/details.aspx? FamilyID=836778ea-b2f2-4907-b2dc- a152ec0a4bc4&displaylang=en  x64: http://www.microsoft.com/downloads/details.aspx?f amilyid=6C15B777-8D9E-4D99-B359- A98E2C0880F7&displaylang=en
  20. 20. 20daniel.fisher@devcoach.biz
  21. 21. 21  HTTP Handler  HTTP Module
  22. 22. 22 public class MyRewriterModule : IHttpModule { public virtual void Init(HttpApplication app) { app.AuthorizeRequest += RewriteRequest; } protected void RewriteRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication) sender; HttpContext.Current.RewritePath("My.aspx?id=42"); } ... }
  23. 23. 23 <configuration> <system.web> <httpModules> <add type="MyRewriterModule, App_Code" name="ModuleRewriter" /> </httpModules> <!–- or --> <httpHandlers> <add verb="*" path="*.aspx" type="MyRewriterFactoryHandler, App_Code" /> </httpHandlers> </system.web> </configuration>
  24. 24. 24 Utilizing HttpContext.RewritePath() Method
  25. 25. 25
  26. 26. 26  Code your own matching logic   Code your own rule provider   Code your own replace mechanizm 
  27. 27. 27  IIS 7 is configured to not authenticate content that is not handled internally  A virtual URL points to an non-existent file  You need to enable URL Authentication on rewriten requests  A) Change preCondition of UrlAuthenticationModule  B) Call Authentication yourself
  28. 28. 28
  29. 29. 29  A gerneric module to redirect calls to URLs to ASP.NET Page endpoints.  Namespace: System.Web.Routing  Built for the ASP.NET MVC Framework
  30. 30. 30 RouteTable is created UrlRoutingModule intercepts the request MvcHandler executes Controller executes RenderView method is executed
  31. 31. 31  Each URL Rewrite is defined as entry of the RouteTable.  In MVC the Route Table maps URLs to controllers.  It is setup in the Global.asax
  32. 32. 32 <configuration> … <system.web> … <httpModules> … <add name="urlRouting" type="System.Web.Routing.UrlRoutingModule"/> </httpModules> …
  33. 33. 33 <%@ Application Language="C#" %> <script runat="server"> static void RegisterRoutes() { RouteTable.Routes.Add( new Route( "articles", new MyRoutingPageHandler())); } …
  34. 34. 34 public class RoutingPageHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { var pathData = requestContext.RouteData.Route.GetVirtualPath( requestContext, requestContext.RouteData.Values); return pathData.VirtualPath.Contains("articles") ? (IHttpHandler)BuildManager. CreateInstanceFromVirtualPath( "~/Default.aspx", typeof(Page)) : (IHttpHandler)BuildManager. CreateInstanceFromVirtualPath( "~/Default2.aspx", typeof(Page)); } …
  35. 35. 35 Create and handle routes NOTE: Don't forget to add the required extension if you're trying this with IIS 6…
  36. 36. 36
  37. 37. 37 RouteTable.Routes.Add( new Route( "articles/{id}", new MyRoutingPageHandler()));
  38. 38. 38 var queryString = new StringBuilder("?"); var serverUtil = httpContext.Server; // Copy route data... foreach (var aux in requestContext.RouteData.Values) { queryString.Append(serverUtil.UrlEncode(aux.Key)); queryString.Append("="); queryString.Append( serverUtil.UrlEncode(aux.Value.ToString())); queryString.Append("&"); }
  39. 39. 39
  40. 40. 40 requestContext.HttpContext.RewritePath( string.Concat( virtualPath, queryString)); (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath( virtualPath, typeof(Page));
  41. 41. 41  ASP.NET has no clue that a request is "routed" and authenticates the requested URL – the virtual path 
  42. 42. 42 var modules = e.HttpContext.ApplicationInstance.Modules; if (modules["UrlAuthorization"] != null && UrlAuthorizationModule.CheckUrlAccessForPrincipal( e.VirtualPath, e.HttpContext.User, e.HttpContext.Request.HttpMethod)) { return; } if (e.HttpContext.GetAuthenticationMode() != AuthenticationMode.Forms) { return; } e.VirtualPath = FormsAuthentication.LoginUrl; e.QueryString = string.Concat( "?ReturnUrl=", e.HttpContext.Server.UrlEncode( e.HttpContext.Request.RawUrl));
  43. 43. 43 Parameters, QueryStrings and FormsAuthentication NOTE: Don't forget to add the required extension if you're trying this with IIS 6…
  44. 44. 44
  45. 45. 45daniel.fisher@devcoach.biz
  46. 46. 46 public class Form : HtmlForm { protected override void RenderAttributes(HtmlTextWriter writer) { writer.WriteAttribute("name", Name); Attributes.Remove("name"); writer.WriteAttribute("method", Method); Attributes.Remove("method"); Attributes.Render(writer); Attributes.Remove("action"); if (!string.IsNullOrEmpty(ID)) { writer.WriteAttribute("id", ClientID); } } }
  47. 47. 47 _context.Response.Filter = new ResponseFilter(_context.Response.Filter); ... public override void Write(byte[] buffer, int offset, int count) { if (HttpContext.Current.Items["VirtualPath"] != null) { var str = Encoding.UTF8.GetString(buffer); var path = HttpContext.Current.Request.Url.PathAndQuery; str = str.Replace( string.Concat( "="", path.Substring(path.LastIndexOf("/") + 1), """), string.Concat( "="", (string)HttpContext.Current.Items["VirtualPath"], """)); buffer = Encoding.UTF8.GetBytes(str); } _sink.Write(buffer, offset, count); }
  48. 48. 48
  49. 49. 49  URL rewriting is used to manipulate URL paths before the request is handled by the Web server.  The URL-rewriting module does not know anything about what handler will eventually process the rewritten URL.  In addition, the actual request handler might not know that the URL has been rewritten.  ASP.NET routing is used to dispatch a request to a handler based on the requested URL path.  As opposed to URL rewriting, the routing component knows about handlers and selects the handler that should generate a response for the requested URL.  You can think of ASP.NET routing as an advanced handler-mapping mechanism.
  50. 50. 50 The presentation content is provided for your personal information only. Any commercial or non-commercial use of the presentation in full or of any text or graphics requires a license from copyright owner. This presentation is protected by the German Copyright Act, EU copyright regulations and international treaties.

    Be the first to comment

    Login to see the comments

Url rewriting mit iis, asp.net und routing engine

Views

Total views

884

On Slideshare

0

From embeds

0

Number of embeds

6

Actions

Downloads

2

Shares

0

Comments

0

Likes

0

×