【问题标题】:How to create Handler which do not change HttpContext if not needed? (Asp.Net MVC)如果不需要,如何创建不更改 HttpContext 的处理程序? (Asp.Net MVC)
【发布时间】:2019-08-13 20:37:50
【问题描述】:

我想创建收集所有 URL 的处理程序,我检查 URL,然后继续“处理”。这意味着,如果 URL 是 www.mysite.com/Contact,它会调用我的处理程序并在 www.mysite.com/Contact 中继续。我不想调用 Redirect 或类似的东西。

问题是,它不能传递内容和脚本。这意味着所有的 css、js 和图像文件都没有通过。例如,我有空的 ProcessRequest(HttpContext context) 函数,它会阻止文件。问题是如何继续(加载所有文件)?

这就是我注册处理程序的方式

<system.webServer>
    <handlers>
      <add name="MyHandler" path="*" verb="*" type="MyWebApp.MytHandler" resourceType="Unspecified" preCondition="integratedMode" />
    </handlers>
  </system.webServer>

我试过了

public void ProcessRequest(HttpContext context)
        {
            context.Response.Flush();
        }

但它仍然会阻止所有文件。

如果你问我为什么要这样做,因为我想检查 Url,如果一切正常,它会继续,如果不是我重定向到控制器。检查 URL 并重定向到某个控件或页面很容易,context.Response 有大量示例。也许我做错了,而 Handler 有更好的东西。

【问题讨论】:

    标签: asp.net-mvc response httphandler


    【解决方案1】:

    我解决了,但不确定是否可以。

    public void ProcessRequest(HttpContext context)
            {
                string page = context.Request.Url.PathAndQuery;
                bool continue = true;
                if ( page.Contains("Content/") == true
                        || page.Contains("Scripts/") == true
                        || page.Contains(".ico") == true
                        )
                {
                        continute = false;
    
                        if (page.Contains(".css") == true)
                        {
                            context.Response.ContentType = "text/css";
                            context.Response.TransmitFile(page);
                        }
                        else if (page.Contains(".js") == true)
                        {
                            context.Response.ContentType = "text/javascript";
                            context.Response.TransmitFile(page);
                        }
                        else
                        {
                            // interesting that pictures and audio files doesn't need set ContentType
                            context.Response.TransmitFile(page);
                        }
                    context.Response.Flush(); // don't know if this is needed
                }
                // ...
                // redirection if page is not ok
                // ...
        }
    

    【讨论】:

      【解决方案2】:

      创建一个 Deligating 处理程序。并在应用程序启动时分配处理程序。 使用下面的代码 公共类 SessionInjectionHandler : DelegatingHandler { ContextHeaders contextHeaders = HttpContext.Current.GetContextHeaders();

      在此处替换上下文代码 }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-14
        • 2011-03-06
        相关资源
        最近更新 更多