How to call a HttpHandler via JQuery in MVC

ぐ巨炮叔叔 提交于 2020-01-04 03:17:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!