2009 - Basta!: Url rewriting mit iis, asp.net und routing engine
-
Upload
daniel-fisher -
Category
Software
-
view
33 -
download
0
Transcript of 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®
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®
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®
4
Agenda
Nice URLs
URL Rewriting IIS Rewriting Module Classic ASP.NET ASP.NET Routing Engine
Solving Postback Issues
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}
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.
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…
11
Inside Internet Information Services
Operating System
HTTP.SYS
Internet Information Services
InetInfo• Metaba
se
Application Pool – W3WP.exe
WebApp• Global• Modules• Handler
15
IIS URL Rewrite Module
Rule based
UI (IISMGR)
ISAPI extension
Global and distributed rewrite rules
…
It's Infrastructure!
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="^([^=&]+)=([^=&]+)$" /> </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>
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!
19
Download
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?familyid=6C15B777-8D9E-4D99-B359-A98E2C0880F7&displaylang=en
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"); }
...
}
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>
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
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
30
Lifecycle of an MVC RequestRouteTable is created
MvcHandler executes
Controller executes
RenderView method is executed
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
32
Configuring the Module
<configuration> …
<system.web> …
<httpModules>
… <add name="urlRouting" type="System.Web.Routing.UrlRoutingModule"/>
</httpModules>
…
33
Register Routes in Global.asax
<%@ Application Language="C#" %>
<script runat="server">
static void RegisterRoutes(){ RouteTable.Routes.Add( new Route( "articles", new MyRoutingPageHandler()));
}…
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));
}…
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…
37
Parameters in a Route
RouteTable.Routes.Add(
new Route(
"articles/{id}", new MyRoutingPageHandler()));
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("&");
}
40
Let's cheat a bit…
requestContext.HttpContext.RewritePath( string.Concat( virtualPath, queryString));
(IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(
virtualPath,
typeof(Page));
41
A word on security… ASP.NET has no clue that a request is
"routed" and authenticates the requested URL – the virtual path
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));
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…
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); }
}
}
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);}
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.
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.