arame3333
arame3333

Reputation: 10193

How to call a HttpHandler via JQuery in MVC

I haven't used httpHandlers before in MVC. However I want to stop session timing out in my application. I found the solution here; http://www.dotnetcurry.com/ShowArticle.aspx?ID=453

However with my implimentation I get the error message

The controller for path '/Shared/KeepSessionAlive.ashx' was not found or does not implement IController

So the jquery;

$.post("/Shared/KeepSessionAlive.ashx", null, function () {
    $("#result").append("<p>Session is alive and kicking!<p/>");
});

is looking for a controller. How do I stop this and execute the handler code instead?

I tried putting this in my web.config;

<httpHandlers>
    <add verb="*" path="KeepSessionAlive.ashx" type="XXXXXX.Views.Shared.KeepSessionAlive"/>
</httpHandlers>

Upvotes: 3

Views: 2642

Answers (1)

Ant P
Ant P

Reputation: 25221

Try ignoring .ashx files in your routes, so MVC won't try and route this to a controller action:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("Shared/{resource}.ashx/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

This will cause MVC routing to ignore .ashx files in /shared/; however, it won't work for .ashx files in other places. If you want it to work in all subdirectories, try the following instead (credit to this answer for this trick):

routes.IgnoreRoute("{*allashx}", new { allashx = @".*\.ashx(/.*)?" });

Upvotes: 3

Related Questions