edit Global.asax file and implement it in website - asp.net

I have website running which contains Global.asax file and App_global.asax.compiled also App_global.asax.dll but now i want to edit or add some existing code of url rewriting.
but when i do code in global.asax file it is not taking.
After lot of googling and search's i come to know i have to compile that global file again after changes done. but i cant do it as the websi## Heading ##te is live and i dont have the solution for it.
Existing code in Global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext myContext=HttpContext.Current;
Regex rewrite_regex = new Regex(#"(.+)\/((.+)\.*)", RegexOptions.IgnoreCase);
try
{
// 'see if we need to rewrite the URL
Match match_rewrite =rewrite_regex.Match(myContext.Request.Path.ToString());
string str = match_rewrite.Groups[2].Captures[0].ToString();
string root = match_rewrite.Groups[0].Captures[0].ToString();
if (Regex.Match(root, "/News/", RegexOptions.IgnoreCase).Success)
{
myContext.RewritePath("~/Default2.aspx?nid="+str);
}
else if (Regex.Match(root, "/Search/", RegexOptions.IgnoreCase).Success)
{
myContext.RewritePath("~/Default.aspx?text=" + str);
}
else if (Regex.Match(root, "/Find/", RegexOptions.IgnoreCase).Success)
{
myContext.RewritePath("~/Default.aspx?text=" + str);
}
Any help will be greatful.

Since you don't have the code the easier way will be to use the IIS redirect rules?
This will add the rules to your web.config. You can create multiple regex-based rules to satisfy your different conditions
e.g.
<rule name="Redirect from blog">
<match url="^blog/([_0-9a-z-]+)/([0-9]+)" />
<action type="Redirect" url="article/{R:2}/{R:1}" redirectType="Found" />
</rule>

Related

URL Rewriting exceptional case for removing .aspx extension

My scenario is: I have a website which is ASP.NET WebForm. Users can create their own page on my web site, their page url would be something like this: (MyWebsite.com/UserPage). but It is actually: (MyWebsite.com/UserPages.aspx?q=UserPage). It means when you enter the url (MyWebsite.com/UserPage) It rewrites the url and shows you (MyWebsite.com/UserPages.aspx?q=UserPage) (but the address bar is always like (MyWebsite.com/UserPage).
Here's my code in my "UrlRewriting" class:
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app.Request.Path.Contains("/") && !app.Request.Path.Contains(".") && app.Request.Path.IndexOf("/") == app.Request.Path.LastIndexOf("/"))
{
string userPageTitle = app.Request.Path.Substring(app.Request.Path.IndexOf("/") + 1);
if (!string.IsNullOrEmpty(userPageTitle ))
{
app.Context.RewritePath(string.Format("UserPages.aspx?q={0}", userPageTitle));
}
}
}
Now here's my problem: as I said my project is ASP.NET WebForm, (So, all of pages have .aspx extension) I wanted to remove the .aspx extension in my Urls, I've tried some codes in web.config which were working properly (In normal cases), but In my case, if you enter (MyWebsite.com/UserPage) It will be considering this "UserPage", as "UserPage.aspx". How can I handle this?
I usually do this with Routing which is available in ASP.NET Web Forms 4+.
You register your routes (URL patterns) in Global.asax, and specify which ASPX page will handle that URL.
This example would have UserPage.aspx handle all URLs that weren't otherwise handled by other ASPX pages.
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("UserPageRoute", "{*url}", "~/UserPage.aspx");
}
Then in your UserPage.aspx you can determine the URL requested by looking at the Request.Url object, eg. Request.Url.PathAndQuery.
Note that you may need some extra web.config settings for this to work, eg (to manage extensionless URL requests)...
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />

ASP.NET enable dot sign web.config

I need to redirect www.domain.com/.well-known/pki-validation/godaddy.html from my webpage to get SSL Certificate from godaddy. but when im given the file path from the web.config file to redirect to it suddenly my site not working. the reason is dot sign.
Please can you guys help me to figure this out.
Thanks
Give proper url with http:\\
protected void Page_Load(object sender, EventArgs e)
{
string url= WebConfigurationManager.AppSettings["url"].ToString();
Response.Redirect(url);
}
<appSettings>
<add key="url" value="your url""/>
<add key="SiteName" value="New York Times"/>
</appSettings>

MVC: Serve file with http header

I am trying to follow this guide and store files in a sub-folder.
However, the OneSignal guide asks to serve these files with additional HTTP header Service-Worker-Allowed: /. How do I do that in Asp.Net MVC?
You can use in your controller's action :
this.Response.Headers.Add("Service-Worker-Allowed","/");
Hope this help :-)
Edit :
A better way to do this is to create an action filter to automatically add this header :
public class WorkerAllowedAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.Headers.Add("Service-Worker-Allowed", "/");
base.OnActionExecuted(filterContext);
}
}
And you can put it on your action (or your controller) :
public partial class HomeController
{
[WorkerAllowed]
public ActionResult Index()
{
return View();
}
}
No matter what I tried, I could not get the scope allowed even though I could see it in the response header. I figured out a solution based on this article: https://weblog.west-wind.com/posts/2015/Nov/13/Serving-URLs-with-File-Extensions-in-an-ASPNET-MVC-Application
Basically, we are making the service worker js file appear that it 'lives' in the root directory to avoid scope issues. You can leave your service worker js file in whatever directory you want (probably /Scripts). Then you set up an IIS rewrite rule in web.config (or in IIS) that re-routes any request that includes the service worker file name to an action (be sure you specify the exact path to the action). The action then returns the file as type javascript/application.
<system.webServer>
<rewrite>
<rules>
<rule name="Service worker fix">
<match url="pwa-sw.js"/>
<action type="Rewrite" url="/home/serviceworker"/>
</rule>
</rules>
</rewrite>
</system.webServer>
Then the controller
[AllowAnonymous]
[Route("serviceworker")]
public ActionResult serviceworker()
{
return File("/Scripts/pwa-sw.js", "application/javascript");
}

Fastest way to rewrite only one subpath

I have a website developed in Classic ASP.NET and running on IIS 7.5. It works okay. But now I have the task to add affiliate program to my website. I want my reflink to looks like www.mywebsite.com/r/userid. Well, I googled around and found I can:
Use UrlRewrite third-party HttpModules. As I understand, they are based on runAllManagedModulesForAllRequests="true" web.config setting. Theoretically, I can:
Set runAllManagedModulesForAllRequests="true" and do RewritePath in Application_BeginRequest manually. But my Application_BeginRequest already contains a bit of code. It is too heavy to send all pages, images etc. to Application_BeginRequest because of one rarely called URL.
So, the question is how can I rewrite only subpath that starts with www.mywebsite.com/r/, and do not call Application_BeginRequest for every image, css etc.? Best if no third-party things.
Well, finished up with HttpModule.
web.config:
<system.webServer>
<modules>
<add name="ReflinkModule" preCondition="" type="www.ReflinkModule" />
</modules>
</system.webServer>
ReflinkModule.cs:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
public void BeginRequest(Object source, EventArgs e)
{
if (HttpContext.Current == null)
return;
if (HttpContext.Current.Request == null)
return;
if (HttpContext.Current.Request.RawUrl == null)
return;
string start = "/r/";
if (!HttpContext.Current.Request.RawUrl.StartsWith(start))
return;
string key = HttpContext.Current.Request.RawUrl.Substring(start.Length);
HttpContext.Current.RewritePath("~/Xxxxx.aspx?r=" + key);
}

Using ASP.NET routing to serve static files

Can ASP.Net routing (not MVC) be used to serve static files?
Say I want to route
http://domain.tld/static/picture.jpg
to
http://domain.tld/a/b/c/picture.jpg
and I want to do it dynamically in the sense that the rewritten URL is computed on the fly. I cannot set up a static route once and for all.
Anyway, I can create a route like this:
routes.Add(
"StaticRoute", new Route("static/{file}", new FileRouteHandler())
);
In the FileRouteHandler.ProcessRequest method I can rewrite the path from /static/picture.jpg to /a/b/c/picture.jpg. I then want to create a handler for static files. ASP.NET uses the StaticFileHandler for this purpose. Unfortunately, this class is internal. I have tried to create the handler using reflection and it actually works:
Assembly assembly = Assembly.GetAssembly(typeof(IHttpHandler));
Type staticFileHandlerType = assembly.GetType("System.Web.StaticFileHandler");
ConstructorInfo constructorInfo = staticFileHandlerType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
return (IHttpHandler) constructorInfo.Invoke(null);
But using internal types doesn't seem to be the proper solution. Another option is to implement my own StaticFileHandler, but doing so properly (supporting HTTP stuff like ranges and etags) is non-trivial.
How should I approach routing of static files in ASP.NET?
Why not use IIS to do this? You could create a redirect rule to point any requests from the first route to the second one before it even gets to your application. Because of this, it would be a quicker method for redirecting requests.
Assuming you have IIS7+, you would do something like...
<rule name="Redirect Static Images" stopProcessing="true">
<match url="^static/?(.*)$" />
<action type="Redirect" url="/a/b/c/{R:1}" redirectType="Permanent" />
</rule>
Or, if you don't need to redirect, as suggested by #ni5ni6:
<rule name="Rewrite Static Images" stopProcessing="true">
<match url="^static/?(.*)$" />
<action type="Rewrite" url="/a/b/c/{R:1}" />
</rule>
Edit 2015-06-17 for #RyanDawkins:
And if you're wondering where the rewrite rule goes, here is a map of its location in the web.config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<!-- rules go below -->
<rule name="Redirect Static Images" stopProcessing="true">
<match url="^static/?(.*)$" />
<action type="Redirect" url="/a/b/c/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
After digging through this problem for a few hours, I found that simply adding ignore rules will get your static files served.
In RegisterRoutes(RouteCollection routes), add the following ignore rules:
routes.IgnoreRoute("{file}.js");
routes.IgnoreRoute("{file}.html");
I've had a similar problem. I ended up using HttpContext.RewritePath:
public class MyApplication : HttpApplication
{
private readonly Regex r = new Regex("^/static/(.*)$", RegexOptions.IgnoreCase);
public override void Init()
{
BeginRequest += OnBeginRequest;
}
protected void OnBeginRequest(object sender, EventArgs e)
{
var match = r.Match(Request.Url.AbsolutePath);
if (match.Success)
{
var fileName = match.Groups[1].Value;
Context.RewritePath(string.Format("/a/b/c/{0}", fileName));
}
}
}
I came up with an alternative to using the internal StaticFileHandler. In the IRouteHandler I call HttpServerUtility.Transfer:
public class FileRouteHandler : IRouteHandler {
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
String fileName = (String) requestContext.RouteData.Values["file"];
// Contrived example of mapping.
String routedPath = String.Format("/a/b/c/{0}", fileName);
HttpContext.Current.Server.Transfer(routedPath);
return null; // Never reached.
}
}
This is a hack. The IRouteHandler is supposed to return an IHttpHandler and not abort and transfer the current request. However, it does actually achieve what I want.
Using the internal StaticFileHandler is also somewhat a hack since I need reflection to get access to it, but at least there is some documentation on StaticFileHandler on MSDN making it a slightly more "official" class. Unfortunately I don't think it is possible to reflect on internal classes in a partial trust environment.
I will stick to using StaticFileHandler as I don't think it will get removed from ASP.NET in the foreseeable future.
You need to add TransferRequestHandler for handling your static files.Please see following answer
https://stackoverflow.com/a/21724783/22858

Resources