ASP.NET 3.5 Url Routing Not Working - c#

I am a newbie to asp.net field and having some problem in implementing url routing in asp.net 3.5 (I know it can be easily implemented in asp.net 4.0).
Here is what I have done.....
a) I am using .NET Framework 3.5 SP1.
b) Added System.Web.Routing assembly reference in web.config
<assemblies>
<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
c) Add the UrlRoutingModule HTTP Module
<httpModules>
<add name="RoutingModule"
type="System.Web.Routing.UrlRoutingModule, System.Web.Routing,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
d) Code in Global.asax
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private static void RegisterRoutes()
{
System.Web.Routing.RouteTable.Routes.Add(
"SaveUser", new System.Web.Routing.Route("SaveUser",
new RouteHandler("~/Register.aspx")));
}
e) RouteHandler.cs Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Compilation;
using System.Web.UI;
public class RouteHandler : IRouteHandler
{
public RouteHandler()
{
}
public RouteHandler(string virtualPath)
{
_virtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//var display = BuildManager.CreateInstanceFromVirtualPath(
// _virtualPath, typeof(Page)) as IDisplay;
var abc = BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(Page)) as IDisplay;
return abc;
}
string _virtualPath;
}
f) Code in Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("~/SaveUser");
}
}
and I am getting the following error
The route handler 'RouteHandler' did not return an IHttpHandler
from its GetHttpHandler() method.
I tried 100 of links but could not make out what is wrong.
If anyone have experience in url routing in asp.net 3.5.....pls help.... I need to implement it very urgently....
Thanks in advance....

System.Web.Routing
only available on .net framework version 4

This is probably too little, too late, but I recently upgraded a .NET 3.5 ASP.NET site to use routing and I see your issue.
The problem is that when you configure the routing module, it creates a 2nd context for the routing module that is completely separate from HttpContext.Current in the ASP.NET page. So, you need to set up your handler so that you can access this other context instance (which happens to be a RequestContext).
public class RouteHandler : IRouteHandler
{
public RouteHandler()
{
}
public RouteHandler(string virtualPath)
{
_virtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//Record the request context of the routing module in HttpContext.Current, so we can use it in pages.
HttpContext.Current.Items("requestContext") = requestContext
return BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(Page)) as IDisplay;
}
string _virtualPath;
}
Now, in the page, you need to access the context from HttpContext.Current.Items.
public partial class _Default : System.Web.UI.Page
{
private readonly RequestContext RequestContext
{
get { return (RequestContext)HttpContext.Current.Items("requestContext"); }
}
protected void Page_Load(object sender, EventArgs e)
{
RequestContext.HttpContext.Response.Redirect("~/SaveUser");
}
}

I've been struggling with this same problem, and here's one thing I've learned. On the page referenced by Rick Schott, it says that what you put in web.config depends on what version of IIS you're deploying to. Use this for IIS 6, or IIS 7 in "classic mode":
<httpModules>
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing,
Version=3.5.0.0,
Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
...but in IIS 7+ "integrated mode", add this instead:
<system.webServer>
<modules>
<remove name="UrlRoutingModule" />
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing,
Version=3.5.0.0,
Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</modules>
</system.webServer>
One important thing I've discovered is that though the latter may be what's correct for your IIS, the former is what works inside Visual Studio 2008. So you may have to deploy a different web.config from the one you develop with.
Another useful fact I've found which isn't well documented is that the path pattern you feed to the Route constructor is app-relative, not host-relative, and it should not start with a leading "/" or "~/". Just start with the first subfolder name, or page name if at app root level.
You have to get all that right just to enable it to invoke your IRouteHandler. Then you can worry about the two-contexts issue, if any. I had no trouble writing to requestContext.HttpContext.Items in the handler class and then reading from Context.Items in the target page.
But since you got the error message "did not return an IHttpHandler from its GetHttpHandler()", it sounds like you've got that working at least on your desktop. So the question then is... why are you casting your page instance as IDisplay instead of as IHttpHandler? That seems like the obvious first thing to change. I tried casting the return as Page and it seems to just want a direct cast to IHttpHandler instead.

Related

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);
}
}
}

Calling a Library Function from a View (MVC C#)

I have a function in my Misc library in App_Code called EncodePicture which encodes a picture. However when I try to call the code, I get the function exists in both. I've looked at other answer such as clearing down the temporary files, I did that but it didn't work. The Misc Library has No namespace, does it need it?
I'm calling the function as :-
<img id="imgTitle" src="data:image/png;base64,#Misc.EncodePicture("/aPic/banner.jpg")" alt="" width="468" height="60" />
I get it Misc exists in both Universe and App_Code.....
How can I get round this problem? The function is :-
using System.Security.Cryptography;
namespace Universe
{
public class Misc
{
public static string EncodePicture(string sFilename)
{
string sEncode = "";
using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("~" + sFilename), FileMode.Open))
{
System.IO.BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
sEncode = Convert.ToBase64String(bytes, 0, bytes.Length);
}
return sEncode;
}
Please don't say hard code the value because I'm going to be using this style in other places and can't hard code all the images. C# or VB.NET pls.
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0433: The type 'Misc' exists in both 'App_Code.keoe0a1i, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Universe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
Qualify via Namespace
Depending on where your EncodePicture() method is defined, you can import the appropriate namespace so that it could be called within your View :
namespace YourProject
{
public static class Misc
{
public static string EncodePicture(string file)
{
// Build a URL for the requested path
return file;
}
}
}
and then simply add a using statement within your View :
#using YourProject;
And you should then be able to call it as expected via :
#Misc.EncodePicture(...)
Or without the using statement in a fully qualified manner :
#YourProject.Misc.EncodePicture(...)
Reference it anywhere via the web.config
If this was a method you would expect to use throughout various different Views, then you might consider adding the namespaces in your web.config so that it would be accessibly more easily :
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<!-- Add your namespace here -->
<add namespace="YourProject" />
</namespaces>
</pages>
</system.web.webPages.razor>

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).

Implement autofac in asp.net web form

I am developing ASP.net Web Form, and I want to implement AutoFac into the website.
I have followed the steps in following link:
https://autofaccn.readthedocs.io/en/latest/integration/webforms.html
But I got this error:
This module requires that the HttpApplication (Global Application Class) implements IContainerProviderAccessor.
I can't find Global.asax.cs in my project, only Global.asax.
Global.asax:
<%# Application Language="C#" %>
<%# Import Namespace="Autofac" %>
<%# Import Namespace="Autofac.Integration.Web" %>
<script RunAt="server">
public class Global : HttpApplication, IContainerProviderAccessor {
// Provider that holds the application container.
static IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public IContainerProvider ContainerProvider {
get { return _containerProvider; }
}
void Application_Start(object sender, EventArgs e) {
// Code that runs on application startup
// Build up your application container and register your dependencies.
var builder = new ContainerBuilder();
//builder.RegisterType<SomeDependency>();
// ... continue registering dependencies...
// Once you're done registering things, set the container
// provider up with your registrations.
_containerProvider = new ContainerProvider(builder.Build());
}
}
</script>
Any ideas? Thank you very much!
I had this problem too and fixed it by creating a global.asax.cs file and referencing this from the original global.asax file. This enables you to implement the required IContainerProviderAccessor interface.
File: Global.asax
<%# Application Codebehind="Global.asax.cs" Inherits="MyCompany.WebForms.Global" Language="C#" %>
File: Global.asax.cs
using Autofac;
using Autofac.Core;
using Autofac.Integration.Web;
using ....
namespace MyCompany.WebForms
{
public partial class Global : HttpApplication, IContainerProviderAccessor
{
// Provider that holds the application container.
static IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
protected void Application_Start(object sender, EventArgs e)
{
....
}
}
}
After implementing this, I also had problems with Could not load type 'MyCompany.WebForms.Global' errors until I moved Global.asax.cs file into the App_Code folder and updated the CodeBehind reference Global.asax.
<configuration>
<system.web>
<httpModules>
<!-- This section is used for IIS6 -->
<add
name="ContainerDisposal"
type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
<add
name="PropertyInjection"
type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/>
</httpModules>
</system.web>
<system.webServer>
<!-- This section is used for IIS7 -->
<modules>
<add
name="ContainerDisposal"
type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"
preCondition="managedHandler"/>
<add
name="PropertyInjection"
type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"
preCondition="managedHandler"/>
</modules>
</system.webServer>
</configuration>
These sections must be defined in the web.config file in order for injection to work.
See https://code.google.com/p/autofac/wiki/WebFormsIntegration#Implement_IContainerProviderAccessor_in_Global.asax

Url Rewriting of aspx page.pls give me suggestion

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. :)

Categories