Using custom virtual paths - asp.net

I'm making a test solution with just 2 or 3 pages organized in folders like this:
And when I run the app I get an url like this:
There is any way to maintain that Physical Path but having a different virtual path like
http://localhost:40300/Index.aspx
without the odd word "Views"?

Take a look at the URL Rewrite module for IIS. As an alternative, you can create a custom HTTP module that will rewrite the virtual path appropriately:
public class MyRewriteHttpModule : IHttpModule
{
// ...
public void Init(HttpApplication app)
{
app.AuthenticateRequest += Application_AuthenticateRequest;
}
private void Application_AuthenticateRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var path = app.Request.Url.PathAndQuery;
if (!path.StartsWith("/Views/", StringComparison.OrdinalIgnoreCase))
app.Context.RewritePath("/Views/" + path);
}
}

Related

Custom HTTP handler for URL rewriting + session and application variable

Currently my product page URL is like
http://www.localhost:80/products/default.aspx?code=productCode
I want to access product page with
http://www.localhost:80/productCode
I have used HTTP module for this.
public class UrlRewritingModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (some condition)
{
context.RewritePath(url);
}
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
//We set back the original url on browser
HttpContext context = ((HttpApplication)sender).Context;
if (context.Items["originalUrl"] != null)
{
context.RewritePath((string)context.Items["originalUrl"]);
}
}
}
I have register it in web.config and it is working fine. But when I deploy it in IIS that session and application variables are not throwing null referent Exceptions.
Can anyone help me?
Edit: Do it require extra code to access session/ Application variable for rewritten URLs
?
Have you tried using HTTPContext.Current?
I was able to solve issue (accessing session and application variables in subsequent pages rewritten by custom handler) by adding runAllManagedModulesForAllRequests="true" attribute in modules in web.config.

IIS 6, html file/extension, urlrewriting

I use url rewriting on my site (ASP.NET 4.0 / IIS6), instead of aspx I use html. Everything like described here: IIS 6 executing html as aspx . Problem is that when I have any real .html file (html file exists in the site folder) on the site it doesn't open in web-browser. Is it way to resolve this? Thanks!
You can use a custom httpmodule like this:
public class CheckRealHtmlFile : System.Web.IHttpModule
{
public void Dispose()
{
}
public void Init(System.Web.HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
System.Web.HttpApplication app = sender as System.Web.HttpApplication;
if (app != null)
{
System.Text.RegularExpressions.Regex rHtml = new System.Text.RegularExpressions.Regex(#"\.html$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (rHtml.IsMatch(app.Context.Request.Url.AbsolutePath) && !System.IO.File.Exists(app.Context.Server.MapPath(app.Context.Request.Url.AbsolutePath)))
{
//Execute your html -> aspx logic
}
else
return;
}
else
return;
}
}

Log all requests (GET, POST, etc.) for all resources (.aspx, .html, .jpg, etc.) to db/file in asp.net

Is it possible to log all requests (GET, POST, etc.) for all resources (.aspx, .html,.pdf, etc.) to db or file in ASP.NET 4 application?
For the moment we use following:
public class RequestLogger : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(mPreRequestHandlerExecute);
}
void mPreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
StreamReader reader = new StreamReader(app.Request.InputStream);
System.Diagnostics.Debug.WriteLine(reader.ReadToEnd());
}
}
This logger works but only for POST method, in other cases (GET) InputStream length is 0.
Get request do not carry any information other than in url.

How to intercept and pre-process QueryStrings in Asp.Net

We send out registration urls to clients via email. Some of the email clients are turning the url into
url <url>
I think it may be happening when users forward the email onto themselves at which point the email client re-formats the original email (maybe)
E.g.
https://my.app.com/login.aspx?param=var
Becomes
https://my.app.com/login.aspx?param=var%20%3Chttps://my.app.com/login.aspx?param=var%3E
Which rightly produces System.Web.HttpRequestValidationException: A potentially dangerous Request.QueryString value was detected
Where in the code should I intercept these instances and santize the url so that the user is re-directed onto the original form of the url?
global.asax?
Page_Init?
HttpHandler?
Pipeline?
You can catch it in Global Application_BeginRequest or in the same event in an HttpModule.
Global
using System;
using System.Web;
namespace MassageIncomingRequestUrl
{
public class Global : HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication) sender;
string path = app.Context.Request.Url.PathAndQuery;
int pos = path.IndexOf("%20%3C");
if (pos > -1)
{
path = path.Substring(0, pos);
app.Context.RewritePath(path);
}
}
}
}
Module
using System;
using System.Web;
namespace MassageIncomingRequestUrl
{
public class UrlMungeModule : IHttpModule
{
#region IHttpModule Members
public void Init(HttpApplication context)
{
context.BeginRequest += BeginRequest;
}
public void Dispose()
{
//nop
}
#endregion
private static void BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
string path = app.Context.Request.Url.PathAndQuery;
int pos = path.IndexOf("%20%3C");
if (pos>-1)
{
path = path.Substring(0,pos);
app.Context.RewritePath(path);
}
}
}
}
This will get your request processed with the correct query string in the Request, regardless of what you see in the browser address. You may be able to take extra steps to remove the garbage from the reported url but that is mainly just aesthetics.

c# HttpModule to handle pseudo sub-domains

I'm new to development with .NET and working on a personal project. My project will allow users to create their own simple mobile site.
I would like to write a HTTP Module that will handle pseudo sub-domains.
I have already setup my DNS wildcard, so sub.domain.com and xxx.domain.com etc. point to the same application. I want to be able to extract sub and ID parts from sub.domain.com/pageID.html URL and load settings of the page from a database server in order to build and render the page to the client.
I can do it with URL rewrite tools like isapirewrite, but I want my application to be independent from OS so that the server doesn't require installation of any 3rd party app.
Is it possible to do it with HTTP handlers?
Can anyone post an example?
You can check the domain at any time. Where to do it dependings on your application's goals. E.g. if you want to serve different pages depending on the domain you could do like this:
public class MyModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string host = app.Request.Url.Host;
if(host == "first.domain.com")
{
app.Context.RewritePath("~/First.aspx");
}
}
}

Resources