代码改变世界

MVC3 中关于 Ajax 请求 HttpHandler 的配置

2011-07-26 16:18  Michael.青菜  阅读(1237)  评论(7编辑  收藏  举报

今天想在 MVC3 的网站解决方案中使用 Ajax 请求一个 HttpHandler,按照之前 .NET 的做法,中间遇到了些问题,下面我将陈述我的做法以及遇到的问题和解决的方法:

1、在 App_Code 文件夹中添加了一个 HttpHandlerDemo.cs,将类 HttpHandlerDemo 继承了 IHttpHandler 接口,并实现了 IHttpHandler 的两个成员 ProcessRequest 和 IsReusable

using System.Web;

namespace MvcApplication.App_Code
{
publicclass HttpHandlerDemo : IHttpHandler
{
publicvoid ProcessRequest(HttpContext context)
{
context.Response.Write(
"Hello");
}

publicbool IsReusable
{
get { returnfalse; }
}
}
}

2、配置 Web.config,IIS版本为IIS7.0

<system.webServer>
<handlers>
<add name="HttpHandlerTest" path="HttpHandlerDemo.ashx" verb="GET,POST" type="MvcApplication.App_Code.HttpHandlerDemo, App_Code" resourceType="Unspecified" requireAccess="Script"/>
</handlers>
</system.webServer>

3、通过浏览器访问 http://localhost/HttpHandlerDemo.ashx 结果报 404 错误。找原因找了半天,一直以为是 Web.config 的配置有问题,尝试修改了好久也查了写资料,还是没有解决,最后没办法请教了我的头——老王(Richwong),结果老王看了一下一分钟不到就搞定了。

具体解决方法如下:

在 Global.asax.cs 文件中 RegisterRoutes 方法中加了一个忽略后缀为 .ashx 的路由代码

publicstaticvoid RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(
"{resource}.ashx/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
new { controller ="Home", action ="Index", id = UrlParameter.Optional } // Parameter defaults
);
}

这样这个问题就解决了。

初次写博客还望各位园丁多多指教,在此谢过各位!