Url Rewriting of aspx page.pls give me suggestion - c#

I am new in asp.net. I have iis version 6.0. I want to rewrite url. Actually I'm working on a site. When I used this tag in web.config
<urlrewritingnet
rewriteOnlyVirtualUrls="true"
contextItemsPrefix="QueryString"
defaultPage="default.aspx"
defaultProvider="RegEx"
xmlns="http://www.urlrewriting.net/schemas/config/2006/07" >
<rewrites>
<add name="this-is-a-long-page-name" virtualUrl="^~/this-is-a-long-page-name"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/Default.aspx"
ignoreCase="true" />
</rewrites>
</urlrewritingnet>
When I run it, it shows the error "unrecognized configuration section rewriter".

user ,
you need to implement urlrewritemodule , all the requests comes to the urlrewritemodule.
you can write your logic there
public class UrlModule : IHttpModule
{
public virtual void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(this.BaseUrlModule_BeginRequest);
}
public virtual void Dispose()
{
}
protected virtual void BaseUrlModule_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
Rewritethepath(application.Request.Path, application);
}
private void Rewritethepath(string requestedPath, HttpApplication application)
{
application.Context.RewritePath("/yournewurl", String.Empty, QueryString);
}
}
make this entry in your web.config
<httpModules>
<add type="namespace.UrlModule, namespace" name="UrlModule"/>
</httpModules>
Register your httpmodule in your web.config , once everyrequest comes to this you can rewrite the url however you want ,
i recently implemented this and let me know if you need any help, I will defiently help you.

My response doesn't directly answer your question (which is about the UrlRewritingNet library). Instead, I suggest considering Microsoft's official IIS URL Rewrite library, which requires IIS 7.x or IIS Express. The UrlRewritingNet library, though useful a couple years ago, is now a less than ideal way to go about rewriting URLs in IIS/ASP.NET. I offer this suggestion since you mentioned you are new to ASP.NET. :)

Related

Can httpModule "capture" outgoing http requests from a web API hosted on IIS?

I have created a class library test project that has one class which implements the IhttpModule interface.
I have a demo web api project that is hosted on my local IIS and has an HttpPost method which inside uses a class that makes outgoing Http requests at third parties.
As of now it works like a charm for the incoming requests but i want to catch every request that comes and goes from my API. I do not care about the responses.
I have already checked the requests made at the third parties and they are correct.
API's web.config :
<system.webServer>
<modules>
<add name="MyIISModule" type="IisTestProject.MyIISModule" />
</modules>
</system.webServer>
MyIISModule.cs :
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(OnBeginRequest);
}
private void OnBeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication) sender;
File.AppendAllLines("C:\\requestHeaders.txt", new List<string>() {$"{DateTime.Now.ToOADate()}_{app.Context.Request.ToString()}" });
}
public void Dispose()
{
}
I made this so i can just check whenever a request happens.
Is there any way to do this without changing my API's code and using only my HttpModule?
Also i have found this:
HTTP modules can only see requests going through IIS/ASP.NET pipeline, while such outbound requests go through Windows sockets directly, and not through IIS/ASP.NET pipeline.
Is there any way to circumvent this?

ASP .Net MapRequestHandler slow

We have rolled out a classic ASP.Net WebService application with large traffic. Though our database is running quite well (<10 ms response times), most of the time spent in WebServer is in the MapRequestHandler stage.
The issue seems to be deep in the ASP .Net stack and without any information available on net, I am clueless as to how to go about improving it.
We use XML payloads for request/response (if that would help in providing a solution).
Please post you handler code and your config files.
MapRequestHandler - The MapRequestHandler event is used by the ASP.NET infrastructure to determine
request handler for the current request based on the file-name extension of the requested resource. MapRequestHandler is an event that the handlers need to implement, I suspect its stuck at some delegate that maps some custom file.
I suspect its 1) Not finding, looping around to find that custom file handler, you may not 2) using the async handler
You have to chase down the various delegate that use this event and setup a break point
Make sure they are Async & Registered for e.g.
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory" />
Then under the handlers verify
<httpHandlers>
<add verb="*" path="*.MyCustomaspx" type="MyCustomHTTPhandler"/>
</httpHandlers>
In your implementation use the async version base handler
// dervie from Async HttpTaskAsyncHandler
public class MyCustomHTTPhandler: HttpTaskAsyncHandler {
public override Task ProcessRequestAsync(HttpContext context)
{
//throw new NotImplementedException();
//blah blah.. some code
}
}
Last resort, not recommended - from SO here, if your handler/page doesnt modify session variables, you can skip the session lock.
<% #Page EnableSessionState="ReadOnly" %>
If your page does not read any session variables, you can opt out of this lock entirely, for that page.
<% #Page EnableSessionState="False" %>
If none of your pages use session variables, just turn off session state in the web.config.
<sessionState mode="Off" />
Based on this if you want to customize session state just based on your specific page/handler
using System;
using System.Web;
public class CustomSessionStateModule : IHttpModule
{
public void Dispose(){ //.. }
public void Init(HttpApplication context){
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e){
HttpContext currentContext = (sender as HttpApplication).Context;
// here you can filter and turn off/on the session state
if (!currentContext.Request.Url.ToString().Contains("My Custom Handler or Page Value")){
// for e.g. change it to read only
currentContext.SetSessionStateBehavior(
System.Web.SessionState.SessionStateBehavior.ReadOnly);
}
else {
//set it back to default
currentContext.SetSessionStateBehavior(
System.Web.SessionState.SessionStateBehavior.Default);
}
}
}

Enable CORS for static resources in ASP .NET MVC?

I've found plenty of resources regarding CORS in Web APIs and for general controllers in ASP .NET MVC.
However, I'm in a situation where I'd like all static resources (CSS and JS files) inside a specific folder to be downloadable through AJAX as well. In other words, enable CORS for those resources or that folder.
How can I accomplish this? I've found no similar question. They are all related to web APIs or general controllers.
Example adapted from Walkthrough: Creating and Registering a Custom HTTP Module. This should add the header to all .js and .css requests.
Create Module
using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
public HelloWorldModule()
{
}
public String ModuleName
{
get { return "HelloWorldModule"; }
}
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".css") || fileExtension.Equals(".js"))
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
}
}
public void Dispose() { }
}
To register the module for IIS 6.0 and IIS 7.0 running in Classic mode
<configuration>
<system.web>
<httpModules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</httpModules>
</system.web>
</configuration>
To register the module for IIS 7.0 running in Integrated mode
<configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</modules>
</system.webServer>
</configuration>
As you are running MVC, make sure you alter the one in the root (not the Views folder).

With ASP.Net, how do I enable browser caching for static content and disable it for dynamic content?

I have found a lot of good information with regards to getting browsers to avoid caching dynamic content (e.g. .aspx pages), however I have not been successful with getting browsers to cache my static content, specifically css, javascript and image files.
I have been playing with Application_BeginRequest in Global.asax without success. Having a separate server for static content is not an option for us. I would also like to avoid having to configure IIS settings unless they can be controlled from the web.config. Could disabling caching for an aspx page influence the caching of static content that appears on it?
I apologise if this question has been answered previously.
As a starting point for discussion, here is the code behind for my Global.asax file.
public class Global_asax : System.Web.HttpApplication
{
private static HashSet<string> _fileExtensionsToCache;
private static HashSet<string> FileExtensionsToCache
{
get
{
if (_fileExtensionsToCache == null)
{
_fileExtensionsToCache = new HashSet<string>();
_fileExtensionsToCache.Add(".css");
_fileExtensionsToCache.Add(".js");
_fileExtensionsToCache.Add(".gif");
_fileExtensionsToCache.Add(".jpg");
_fileExtensionsToCache.Add(".png");
}
return _fileExtensionsToCache;
}
}
public void Application_BeginRequest(object sender, EventArgs e)
{
var cache = HttpContext.Current.Response.Cache;
if (FileExtensionsToCache.Contains(Request.CurrentExecutionFilePathExtension))
{
cache.SetExpires(DateTime.UtcNow.AddDays(1));
cache.SetValidUntilExpires(true);
cache.SetCacheability(HttpCacheability.Private);
}
else
{
cache.SetExpires(DateTime.UtcNow.AddDays(-1));
cache.SetValidUntilExpires(false);
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetNoStore();
}
}
}
If you are using IIS7 & and you want to cache static content add the following in the web.config as according to the documentation:
<configuration>
<system.webServer>
<staticContent>
<clientCache httpExpires="Sun, 27 Sep 2015 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>
</system.webServer>
</configuration>
The magic is made by HTTP headers - see this page.

HttpModule and WCF (AspNetCompatibilityRequirementsMode.Allowed)

I'm hosting WCF services in Asp.net web page in ASP.NET Compatibility Mode
(AspNetCompatibilityRequirementsMode.Allowed). I've written simple HttpModule:
public class ExceptionInterceptor : IHttpModule
{
public ExceptionInterceptor()
{
}
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.Error += new EventHandler(context_Error);
}
void context_Error(object sender, EventArgs e)
{
// do something
}
}
web.config:
<httpModules>
<add name="ExceptionInterceptor" type="HttpModules.ExceptionInterceptor, HttpModules"/>
</httpModules>
My question is, why after occurence of unhandled exception in service, the code do not enter in context_Error(object sender, EventArgs e) function in my module.
What's more, the code do not even enter the Application_Error(object sender, EventArgs e) in Globals.asax.
Can someone explain that to me ?
What is the best option for global exception handling in WCF services ?
Regards
WCF is not ASP.NET - it might be able to use some of ASP.NET's infrastructure, but it's not ASP.NET per se.
In order to handle errors in a WCF service globally, you need to implement the IErrorHandler interface on your service - or plug in a WCF behavior that does this for you.
Check out the MSDN documentation on IErrorHandler - it's quite a simple interface, really. The HandleError method is typically used to log the error on the server to keep track of what's going on, while the ProvideFault method is used to turn the .NET exception on the server into an interoperable SOAP fault to send that back to the calling client (which might be a non-.NET client that can't really deal with a .NET-specific exception).
Rory Primrose has a great blog post about how to package up the IErrorHandler into a WCF service behavior which you can easily add to an existing service just in config - pretty close to magic :-) Also, check out another great post on the topic by Steve Barbour.

Categories