ASP.NET handler not running on IIS7 - asp.net

I've wrote a simple handler:
public class ImageHandler : IHttpHandler, IRequiresSessionState
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
byte[] imgData = context.Session["Data"] as byte[];
if (imgData != null)
{
context.Response.CacheControl = "no-cache";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(imgData);
context.Response.Flush();
}
}
}
And setup the web.config:
<system.web>
<httpHandlers>
<add verb="GET" path="image.png" type="TestWeb.Handlers.ImageHandler, TestWeb" />
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add name="Image" verb="GET" path="image.png" type="TestWeb.Handlers.ImageHandler, TestWeb" />
</handlers>
</system.webServer>
If I run the code allowing VS start a new IIS service and open a new tab it reaches the breakpoint on the handler.
If I set don't open a page. Wait for request from an external application it never reaches the handler.
It is not just the breakpoint, no code from the handler executes when I run the website configured on IIS. It only works if I start from VS.
What did I miss when configuring IIS7 ?

I had to switch the Application Pool to Integrated mode, it was using classic.
And I had to remove the handler configuration from <system.web> because it was giving me error 500.23.
HTTP Error 500.23 - Internal Server
Error An ASP.NET setting has been
detected that does not apply in
Integrated managed pipeline mode.

you need to attach to the asp.net worker process. go to tools/attach to process and choose the w3p process.

Related

Basic custom Http Handler is not even executed

I am trying to learn about the custom Http Handlers. Using VS2019 Community, I created the default ASP.NET Web App with MVC option, target for .NET Framework 4.7.2. Then I defined the custom Http Handler as
namespace WebApplication25
{
public class CustomHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("<h1>WelCome</h1>");
}
}
}
In the file Web.config
<system.webServer>
<handlers>
<add verb="*" path="*.curry" name="CustomHandler" type="WebApplication25.CustomHandler"/>
</handlers>
</system.webServer>
Then during the standard run with localhost I enter
https://localhost:44325/notes.curry
but the code for CustomHandler is not even run. In the browser I get
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404.....

Httphandler for WebDav requests

I am trying to write a asp.net httphandler for handling webdav requests with IIS.
I am extending the IHttpHandler interface and implementing the ProcessRequest.
public class clsMyHandler : IHttpHandler
{
public void ProcessRequest(System.Web.HttpContext context)
{
StreamWriter sw = new StreamWriter(#"C:\requestLog.txt",true);
sw.WriteLine("Got a request at " + DateTime.Now.ToString());
sw.Close();
}
public bool IsReusable
{
get
{
return true;
}
}
}
It's a simple handler for my test purpose to just log into a file when I get the webdav request for a file of given name. I can see the handler listed in the Handler mappings.
This is the web.config
<handlers>
<add name="testhandler" verb="*" path="*e.txt" type="MyPipeLine.clsMyHandler, MyPipeLine" />
</handlers>
It works fine when the request is a http from browser. My handler gets executed and logs in the file. But when the request is webdav(I have enabled webdav with IIS and mapped the website root as a network drive) editing a file of the pattern *e.txt fails which I would expect as I am overriding the webdav handler, but I do not see it getting logged in my file.
I am not sure if there is a server log that I can check to get some clue as to whether or not the handler was invoked and if there is an error in the handler. I am new to this.
I am not finding much materials/guides online regarding httphandlers for webdav.
Appreciate any help.

IIS 7 cannot route requests: error 404, file not found

I've created my first owin/web.api REST service.
Something super simple just to test some features.
I've created an empty project with Visual Studio 2013 and installed a these packages:
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin
Microsoft.Owin.Diagnostics
Microsoft.Owin.Host.SystemWeb
Newtonsoft.Json
Owin
This is my startup class:
[assembly: OwinStartup(typeof(OwinO.Startup))]
namespace OwinO
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
app.UseWelcomePage("/");
app.UseErrorPage();
}
}
}
and this is my Api Controller:
[RoutePrefix("api/v1")]
public class TestController : ApiController
{
[HttpGet]
[Route("test")]
public async Task<IHttpActionResult> Get()
{
string name = "Mister";
string sayHello = string.Empty;
Task<string> t = new Task<string>(() =>
{
sayHello = string.Format("Hello {0}", name);
return sayHello;
});
t.Start();
await t;
return Ok(new string[] { sayHello });
}
}
My Web.Config:
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
<system.webServer>
<!--<modules runAllManagedModulesForAllRequests="true" />-->
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Nothing really too complicated.
PROBLEM:
This Web.Api service works everywhere.
I've tested it on my PC with IIS Express (8.0) and my IIS 7.5 (Windows 7).
I've deployed it to my hosting provider (Arvixe) and it works.
I've deployed it on a server (Windows 2008 Server R2) and it works.
The problem it does not work where it should work.
My client's server is Windows 2008 sp2 (32 bit) with IIS 7.
I've managed to startup Owin but requests cannot be routed.
I cannot access the address: [server ip]/api/v1/test
WHAT I'VE TRIED:
I've checked the server's configuration:
Framework 4.5.1 is installed.
IIS is up and running (I've got other ASP.NET MVC web apps installed)
I've tried to remove the custom routing prefix:
[RoutePrefix("api/v1")]
I've checked the IIS log and the requests reach IIS.
It's just it does not know how to route.
To cross-check the problem I've created a simple web.api without Owin (with the same routing system) and it works.
The same Owin app self-hosted works.
There is not fix for this.
I've spent a good amount of time trying to find a solution or a way to fix it.
After the server upgrade everything worked as expected.

HttpModule isn't processing request authentication

I have an HttpHandler that I'm trying to use to put a little security layer over a certain directory in my site, but it's behaving strangely.
I've got it registered like this in my Web.Config: no longer valid since I'm in IIS 7.5
<httpHandlers>
<add verb="*" path="/courses/*" type="CoursesAuthenticationHandler" />
I can't tell if it's actually being called or not, because regardless of the code, it always seems to do nothing. On the flip side, if there are any errors in the code, it does show me an error page until I've corrected the error.
Here's the handler itself:
using System;
using System.Web;
public class CoursesAuthenticationHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
if (!context.Request.IsAuthenticated)
context.Response.Redirect("/");
}
}
So... that's pretty much it. The handler is being registered and analyzed at compile time, but doesn't actually do what it's expected to.
Edit: I realized that I'm using IIS 7.5 and that does indeed have an impact on this implementation.
For IIS 7, here's the Web.Config registration I used:
<handlers accessPolicy="Read, Execute, Script">
<add name="CoursesAuthenticationHandler"
verb="*"
path="/courses/*"
type="CoursesAuthenticationHandler"
resourceType="Unspecified" />
Edit 2: Progress! When not logged in, requests made to the /courses/ directory are redirected to the login page. However, authenticated requests to the /courses/ directory return empty pages...
Edit 3: Per #PatrickHofman's suggestion, I've switched to using an HttpModule.
The Web.Config registration:
<modules>
<add name="CourseAuthenticationModule" type="CourseAuthenticationModule" />
The code:
using System;
using System.Web;
public class CourseAuthenticationModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
public void BeginRequest(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (request.Path.ToLower().StartsWith("/courses/") && !request.IsAuthenticated)
{
response.Redirect("/");
}
}
}
Now the problem is that !request.IsAuthenticated is always false. If I'm logged in, and navigate to the /courses/ directory, I'm redirected to the homepage.
What's the deal?
I think the last problem lies in the fact that a HttpHander handles stuff. It is the end point of a request.
Since you didn't add anything to the request, the response will end up empty.
Are you looking for HttpModules? They can be stacked.
As a possible solution when only files are necessary: read the files yourself in the request by either reading and writing to response or use TransmitFile. For ASP.NET pages you need modules.

Custom httpModule is not logging to Windows Logs

I have a problem with logging an message to EventViewer\WindowsLogs using a custom HTTPModule class. I've already try to run Visual Studio with admin rights, I also tried from IIS 6.0. It doesn't crash, it just doesn't add any code. Below it's the module class and the config file.
HttpModule
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Diagnostics;
namespace Chapter_V.HttpModules
{
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.AuthenticateRequest += new EventHandler(OnAuthentication);
}
private void OnAuthentication(object sender, EventArgs e)
{
string name = HttpContext.Current.User.Identity.Name;
EventLog log = new EventLog();
log.Source = "My First HttpModule";
log.WriteEntry(name + " was authenticated !");
}
public void Dispose()
{
}
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<httpModules>
<add name="MyHttpModule" type="Chapter_V.HttpModules.MyHttpModule,ChapterV"/>
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="MyHttpModule" type="Chapter_V.HttpModules.MyHttpModule,ChapterV"/>
</modules>
</system.webServer>
</configuration>
Do you have any ideea about this issue? (this is only for study purposes)
Provided the user identity on your application pool has the rights to create event log entries.
Try running the following script:
eventcreate /ID 1 /L APPLICATION /T INFORMATION /SO "My First HttpModule" /D "My first log"
This will create a new event source named "My First HttpModule" under APPLICATION event log as INFORMATION event type.
Not sure of the exact reasons why, but a source must already exist (be created) in the event log before it can be used in code.
Source of information is here

Resources