Top Banner
1 URL Rewriting mit IIS, ASP.NET und Routing Engine Daniel Fisher [email protected] SOFTWARE://DEVELOPMENT+ARCHITECTURE+CONSULTING devcoach®
50

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

Aug 13, 2015

Download

Software

Daniel Fisher
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 2009 - Basta!: Url rewriting mit iis, asp.net und routing engine

1

URL Rewriting mit IIS, ASP.NET und Routing Engine

Daniel [email protected]

SOFTWARE://DEVELOPMENT+ARCHITECTURE+CONSULTING

devcoach®

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

2

Über mich…

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

SOFTWARE://DEVELOPMENT+ARCHITECTURE+CONSULTING

devcoach®

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

3

Über devcoach…

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®

SOFTWARE://DEVELOPMENT+ARCHITECTURE+CONSULTING

devcoach®

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

4

Agenda

Nice URLs

URL Rewriting IIS Rewriting Module Classic ASP.NET ASP.NET Routing Engine

Solving Postback Issues

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

5

NICE URLS

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

[email protected]

What about…

http://www.basta.net/View.aspx?y={7B5BBD55-40F3-4ccb-852D-E6D0DB3D308D}&t={31646FBE-CC9C-43c8-AB77-BE149F2C2B99}&c={070877AA-668D-47d7-872E-5838CD5E2F8B}

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

[email protected]

What about…

http://www.basta.net/2009/Speakers

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

[email protected]

What is a nice URL

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.

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

[email protected]

URL Rewriting

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…

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

[email protected]

URL REWRITING

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

11

Inside Internet Information Services

Operating System

HTTP.SYS

Internet Information Services

InetInfo• Metaba

se

Application Pool – W3WP.exe

WebApp• Global• Modules• Handler

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

12

A Request (IIS 6.x)

HTTP.SYS IIS aspnet_isapi.dll

Module HandlerModuleModuleModule

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

13

Integrated Request (IIS 7.x)

HTTP.SYS IIS Module HandlerModuleModuleModule

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

[email protected]

IIS URL REWRITING MODULE

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

15

IIS URL Rewrite Module

Rule based

UI (IISMGR)

ISAPI extension

Global and distributed rewrite rules

It's Infrastructure!

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

16

Creating rewrite a rule

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

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

17

IIS URL Rewriting Module

Creating a "nice" URL

demo

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

18

IIS URL Rewrite Module

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!

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

[email protected]

CLASSIC ASP.NET URL REWRITING MODULE

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

21

URL Rewrite mit classic ASP.NET

HTTP Handler

HTTP Module

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

22

URL Rewrite mit classic ASP.NET

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"); }

...

}

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

23

URL Rewrite mit classic ASP.NET

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

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

24

Classic ASP.NET URL Rewriting

Utilizing HttpContext.RewritePath() Method

demo

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

25

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

26

Rules?

Code your own matching logic Code your own rule provider Code your own replace mechanizm

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

27

A word on security… 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

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

28

ASP.NET ROUTING ENGINE

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

29

Introducing the Routing Engine

A gerneric module to redirect calls to URLs to ASP.NET Page endpoints. Namespace: System.Web.Routing Built for the ASP.NET MVC Framework

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

30

Lifecycle of an MVC RequestRouteTable is created

MvcHandler executes

Controller executes

RenderView method is executed

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

31

The RouteTable is Created

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

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

32

Configuring the Module

<configuration> …

<system.web> …

<httpModules>

… <add name="urlRouting" type="System.Web.Routing.UrlRoutingModule"/>

</httpModules>

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

33

Register Routes in Global.asax

<%@ Application Language="C#" %>

<script runat="server">

static void RegisterRoutes(){ RouteTable.Routes.Add( new Route( "articles", new MyRoutingPageHandler()));

}…

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

34

The Routing Page Handler

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

}…

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

35

ASP.NET Routing Engine

Create and handle routes

demo

NOTE: Don't forget to add the required extension if you're trying this with IIS 6…

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

36

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

37

Parameters in a Route

RouteTable.Routes.Add(

new Route(

"articles/{id}", new MyRoutingPageHandler()));

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

38

Using Parameters

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("&");

}

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

39

Ups

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

40

Let's cheat a bit…

requestContext.HttpContext.RewritePath( string.Concat( virtualPath, queryString));

(IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(

virtualPath,

typeof(Page));

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

41

A word on security… ASP.NET has no clue that a request is

"routed" and authenticates the requested URL – the virtual path

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

42

FormAuthentication and UrlAuthorization

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

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

43

ASP.NET Routing Engine

Parameters, QueryStrings and FormsAuthentication

demo

NOTE: Don't forget to add the required extension if you're trying this with IIS 6…

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

44

SOLVING POSTBACK ISSUES

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

[email protected]

The Issue

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

46

The easy way…

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); }

}

}

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

47

The more convenient way…

_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);}

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

48

SUMMARY

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

49

IIS Rewriting vs. ASP.NET Routing

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.

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

50

SOFTWARE://DEVELOPMENT+ARCHITECTURE+CONSULTINGdevcoach®

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.