自定义文件扩展名的HTTP处理程序和404错误

时间:2012-10-06 08:57:42

标签: c# asp.net-mvc localization httphandler

对于自定义HTTP处理程序,我有些不太清楚。

我已根据this blog post创建了ScriptTranslator HTTP处理程序 我已通过以下方式在web.config文件中注册了处理程序:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
    <handlers>
        <add name="ScriptTranslatorHandler" path="*.js.axd" verb="*" type="CamelotShiftManagement.HttpHandlers.ScriptTranslator" />
    </handlers>
</system.webServer>

我还在我的global.asax中添加了IgnoreRoute命令,因此web-app可以根据we.config文件启动处理程序。

routes.IgnoreRoute("{resource}.js.axd/{*pathInfo}");

处理程序假设从我的html文件转换JS文件引用,因此我修改了我的脚本引用并在最后添加了axd扩展名。

处理程序接收请求并搜索没有axd扩展的文件以获取需要翻译的脚本内容,这是基本的ProccessRequest操作:

public void ProcessRequest(HttpContext context)
{
    string relativePath = context.Request.AppRelativeCurrentExecutionFilePath.Replace(".axd", string.Empty);
    string absolutePath = context.Server.MapPath(relativePath);
    string script = ReadFile(absolutePath);

    string translated = TranslateScript(script,CultureInfo.CurrentCulture);
    context.Response.Write(translated);
    Compress(context);
    SetHeadersAndCache(absolutePath, context);
}

所以在我的html文件中我只修改了脚本标记的引用,没有名为myscript.js.axd的实际文件,有一个名为myscript.js的文件。

我收到404错误。

我很擅长创建和使用自定义Http Handler,我不知道该用法有什么期望。

引用的blog post意味着代码中不应存在实际的.js.axd文件,并且脚本引用的请求将重新路由到处理程序并使用前2行处理实际的.js文件在我之前提供的代码中。

我是否天气或不设置自定义HTTP处理程序应首先运行处理程序代码然后再抛出404错误,还是应该创建一个虚拟myScript.js.axd文件来支持处理程序操作?

1 个答案:

答案 0 :(得分:3)

忽略网址必须如下:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("Scripts/{resource}.js.axd/{*pathInfo}");

然后添加:

  <system.web>
    <httpHandlers>
      <add path="*.js.axd" verb="*" type="..." />
    </httpHandlers>
    ...
  </system.web>

  <system.webServer>
    ...
    <handlers>
        <add name="ScriptTranslatorHandler" path="*.js.axd" verb="*" type="..." />
    </handlers>
  </system.webServer>

同时检查命名空间,文件ScriptTranslator.cs不包含它

<强>加了:

默认routes.IgnoreRoute("{resource}.axd/{*pathInfo}");只忽略localhost/test.axd,而不是'localhost / Home / test.axd`,然后应用程序尝试查找匹配的路由但找不到它,然后我们收到404。