问题
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>
回答1:
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(/.*)?" });
来源:https://stackoverflow.com/questions/16295917/how-to-call-a-httphandler-via-jquery-in-mvc