Skip to content

Commit 91fc9b1

Browse files
committed
proper url rewriting and requests handling
1 parent 900d538 commit 91fc9b1

File tree

5 files changed

+108
-57
lines changed

5 files changed

+108
-57
lines changed

ExampleWebBasic.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
</ItemGroup>
5252
<ItemGroup>
5353
<Content Include="Global.asax" />
54+
<Content Include="Index.aspx" />
5455
<Content Include="Web.config" />
5556
</ItemGroup>
5657
<ItemGroup>

Global.asax

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
<%@ Application CodeFile="Global.asax.cs" Inherits="WebApp.Global" Language="C#" %>
1+
<%@ Application CodeFile="Global.asax.cs" Inherits="WebApp.Global" Language="C#" %>

Global.asax.cs

Lines changed: 78 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,58 +2,83 @@
22
using System;
33
using System.Collections.Generic;
44
using System.Globalization;
5+
using System.Reflection;
56
using System.Web;
67
using System.Web.Security;
78
using System.Web.SessionState;
89

910
namespace WebApp {
11+
// https://docs.microsoft.com/cs-cz/dotnet/api/system.web.httpapplication?view=netframework-4.8
1012
public partial class Global : System.Web.HttpApplication, IHttpHandler, IRequiresSessionState {
11-
// https://docs.microsoft.com/cs-cz/dotnet/api/system.web.httpapplication?view=netframework-4.8
12-
protected void Application_PostAuthorizeRequest() {
13-
// to start session:
14-
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
15-
}
16-
public void Session_Start(object sender, EventArgs e) {
17-
// Called once when session is started in first request:
13+
14+
15+
16+
17+
18+
/**
19+
* Global.aspx HttpApplication handlers:
20+
*/
21+
22+
// Called only once per session:
23+
protected void Session_Start(object o, EventArgs e) {
1824
HttpContext.Current.Session.Add("RequestCounter", 0);
1925
}
20-
protected void Application_AcquireRequestState (object sender, EventArgs e) {
21-
// Called for every request:
22-
if (this.Request.Path == "/") {
23-
this._demoHandleHome();
24-
} else {
25-
this._demoRedirectAnyOtherPageToHome();
26-
}
26+
27+
// Change rewritten url back to raw url at the request begin:
28+
protected void Application_BeginRequest (object o, EventArgs e) {
29+
this.Request
30+
.GetType()
31+
.GetField("_url", BindingFlags.Instance | BindingFlags.NonPublic)
32+
.SetValue(this.Request, new System.Uri(
33+
this.Request.Url.Scheme + System.Uri.SchemeDelimiter +
34+
this.Request.Url.Authority + this.Request.RawUrl
35+
));
2736
}
28-
protected void Application_PostAcquireRequestState (object sender, EventArgs e) {
29-
// Called for every request:
30-
if (this.Response.StatusCode >= 300 && this.Response.StatusCode <= 400) {
31-
// When request is redirected - call flush and end the request:
32-
this.Response.Flush();
33-
this.Response.End();
37+
// Read session data:
38+
protected void Application_PostAuthorizeRequest (object o, EventArgs e) {
39+
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
40+
}
41+
// Handle all requests execution:
42+
protected void Application_PreRequestHandlerExecute (object o, EventArgs e) {
43+
if (this.Request.Url.LocalPath.IndexOf("/test-redirect") == 0) {
44+
this._demoHandleTestRecorect();
3445
} else {
35-
// Call `Reponse.Flush();` method (not `Response.End();`) to be able to see session panel
36-
TimeSpan reqTimeSpan = DateTime.Now - HttpContext.Current.Timestamp;
37-
string requestTime = reqTimeSpan.Milliseconds.ToString("0.###", new CultureInfo("en-US")) + " ms ("
38-
+ reqTimeSpan.Ticks.ToString() + " ticks)";
39-
this.Response.AddHeader("X-Exec-Time", requestTime);
40-
this.Response.Flush();
46+
this._demoHandleAllRequests();
4147
}
4248
}
43-
private void _demoRedirectAnyOtherPageToHome () {
44-
Debug.Dump("Redirected from: " + this.Request.Path);
49+
// Add execution time header after everything is done:
50+
protected void Application_PostRequestHandlerExecute (object o, EventArgs e) {
51+
TimeSpan reqTimeSpan = DateTime.Now - HttpContext.Current.Timestamp;
52+
string requestTime = reqTimeSpan.Milliseconds.ToString("0.###", new CultureInfo("en-US")) + " ms ("
53+
+ reqTimeSpan.Ticks.ToString() + " ticks)";
54+
this.Response.AddHeader("X-Exec-Time", requestTime);
55+
}
56+
57+
58+
59+
60+
61+
62+
/**
63+
* Demo handler methods:
64+
*/
65+
66+
// Handle demo redirect request:
67+
private void _demoHandleTestRecorect () {
68+
Debug.Dump("Redirected from: " + this.Request.Url.AbsoluteUri);
4569
this.Response.Headers.Add("Location", "/");
46-
this.Response.StatusCode = 302;
70+
this.Response.StatusCode = 302;
4771
}
48-
private void _demoHandleHome () {
72+
// Handle all demo requests:
73+
private void _demoHandleAllRequests () {
4974
// Write some standard output:
50-
this.Response.Write("Hallo ");
75+
this.Response.Write("Hallo world!<br /><br />");
5176

5277
// Try to dump something in debug mode:
5378
try {
5479
this._demoDumpAndLog();
5580
this._demoSession();
56-
this._demoCatchedException();
81+
//this._demoCatchedException();
5782
//this._demoUncatchedException();
5883
} catch (Exception ex) {
5984
// Last exception is:
@@ -67,8 +92,18 @@ private void _demoHandleHome () {
6792
//this._runExceptionsTests();
6893

6994
// Write some standard output:
70-
this.Response.Write("world!");
95+
this.Response.Write(@"<br /><br />Click for <a href=""/test-redirect"">demo redirection</a>.");
7196
}
97+
98+
99+
100+
101+
102+
/**
103+
* Demo dump methods:
104+
*/
105+
106+
// Dump some structured example data:
72107
private void _demoDumpAndLog() {
73108
if (!Debug.Enabled()) return;
74109
var demoObject = new Dictionary<string, object>() {
@@ -98,10 +133,14 @@ private void _demoDumpAndLog() {
98133
Debug.Dump(demoObject);
99134
Debug.Log(demoObject);
100135
}
136+
137+
// Count something in session:
101138
private void _demoSession() {
102139
int requestsCount = (int)this.Session["RequestCounter"];
103140
this.Session["RequestCounter"] = requestsCount + 1;
104141
}
142+
143+
// Render some catched exception:
105144
private void _demoCatchedException () {
106145
try {
107146
throw new Exception("Demo catched exception text.");
@@ -110,13 +149,19 @@ private void _demoCatchedException () {
110149
Debug.Log(ex);
111150
}
112151
}
152+
153+
// Render some uncatched exception:
113154
private void _demoUncatchedException () {
114155
throw new Exception("Demo uncatched exception text.");
115156
}
157+
158+
// Run test dumps:
116159
private void _runDumpingTests () {
117160
var dlTest = new Tests.DumpingAndLoging();
118161
dlTest.TestAll();
119162
}
163+
164+
// Run test exceptions rendering:
120165
private void _runExceptionsTests () {
121166
var eTest = new Tests.ExceptionsRendering();
122167
eTest.TestAll();

Index.aspx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<%@ Page Language="C#" %>

Web.config

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1-
<?xml version="1.0" encoding="utf-8"?>
1+
<?xml version="1.0" encoding="utf-8"?>
22
<!--
33
For more information on how to configure your ASP.NET application, please visit
44
https://go.microsoft.com/fwlink/?LinkId=169433
55
-->
66
<configuration>
77

88
<system.web>
9+
<authentication mode="None" />
910
<compilation debug="true" targetFramework="4.5" />
1011
<httpRuntime targetFramework="4.5" />
11-
<customErrors mode="On" />
12+
<customErrors mode="Off" />
1213
<sessionState mode="InProc" timeout="525600" cookieless="UseCookies" cookieName="ASP.NET_SessionId" regenerateExpiredSessionId="true">
1314
<providers>
1415
<clear />
@@ -19,7 +20,7 @@
1920
<appSettings>
2021
<add key="Desharp:Enabled" value="1" />
2122
<add key="Desharp:Output" value="html" />
22-
<add key="Desharp:DebugIps" value="127.0.0.1,::1,169.254.137.235"/>
23+
<!--add key="Desharp:DebugIps" value="127.0.0.1,::1" /-->
2324
<add key="Desharp:Levels" value="+exception,debug,info,-notice,-warning,+error,+critical,alert,+emergency,javascript" />
2425
<add key="Desharp:Panels" value="Desharp.Panels.SystemInfo,Desharp.Panels.Session" />
2526
<add key="Desharp:Directory" value="~/logs" />
@@ -30,19 +31,19 @@
3031

3132
<modules>
3233
<remove name="OutputCache"/>
33-
<remove name="WindowsAuthentication"/>
34-
<remove name="FormsAuthentication"/>
35-
<remove name="DefaultAuthentication"/>
36-
<remove name="RoleManager"/>
37-
<remove name="UrlAuthorization"/>
38-
<remove name="FileAuthorization"/>
39-
<remove name="AnonymousIdentification"/>
40-
<remove name="Profile"/>
41-
<remove name="UrlMappingsModule"/>
42-
<remove name="ServiceModel-4.0"/>
43-
<remove name="UrlRoutingModule-4.0"/>
44-
<remove name="ScriptModule-4.0"/>
45-
<!-- https://docs.microsoft.com/en-us/iis/configuration/system.webserver/modules/add -->
34+
<remove name="WindowsAuthentication"/>
35+
<remove name="FormsAuthentication"/>
36+
<remove name="DefaultAuthentication"/>
37+
<remove name="RoleManager"/>
38+
<remove name="UrlAuthorization"/>
39+
<remove name="FileAuthorization"/>
40+
<remove name="AnonymousIdentification"/>
41+
<remove name="Profile"/>
42+
<remove name="UrlMappingsModule"/>
43+
<remove name="ServiceModel-4.0"/>
44+
<remove name="UrlRoutingModule-4.0"/>
45+
<remove name="ScriptModule-4.0"/>
46+
<!-- https://docs.microsoft.com/en-us/iis/configuration/system.webserver/modules/add -->
4647
<add name="Desharp" type="Desharp.Module" preCondition="managedHandler" />
4748
</modules>
4849
<caching enabled="false" enableKernelCache="false" />
@@ -59,23 +60,26 @@
5960

6061
<rewrite>
6162
<rules>
62-
<rule name="All to Global.asax" enabled="true" stopProcessing="true">
63+
<rule name="All to empty Index.aspx to handle everything in Global.aspx" enabled="true" stopProcessing="true">
6364
<match url="(.*)" />
64-
<!--conditions logicalGrouping="MatchAll">
65-
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
65+
<conditions logicalGrouping="MatchAll">
6666
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
67-
</conditions-->
68-
<action type="Rewrite" url="{R:1}" />
67+
</conditions>
68+
<action type="Rewrite" url="Index.aspx?{R:1}" />
6969
</rule>
7070
</rules>
7171
</rewrite>
7272

73-
<httpErrors errorMode="Detailed" />
73+
<httpErrors errorMode="Detailed" />
74+
75+
<staticContent>
76+
<mimeMap fileExtension=".md" mimeType="text/x-markdown" />
77+
</staticContent>
7478

7579
</system.webServer>
7680

7781
<runtime>
7882
<loadFromRemoteSources enabled="true" />
7983
</runtime>
8084

81-
</configuration>
85+
</configuration>

0 commit comments

Comments
 (0)