0

I have a typical ASP.NET MVC 4 application and the following scenario, which I couldn't find a suitable solution on the internet.

What I want to do is to "intercept" specifically a text/javascript request from the client, and then before the server sends it, manipulate that javascript, to do some replacements in it, and then the manipulated JS gets transmitted to the client as if nothing happened.

My cshtml is a simple HTML page which has a regular script tag like so:

<script type="text/javascript" src="@Scripts.Url("~/Scripts/home/index.js")"></script>

It tells the browser the script file to load. Now the browser asks the web server for just this file. I can't seem to find any event, module or action filter that lets me manipulate this specific request. I thought that the browser always asks the server, to get any response (even if it is "not modified").

Please note that I know how to intercept a "regular" request (like text/html) and that is working just fine. However I can't seem to find a way to intercept any other request, like the mentioned text/javascript or even images.

I'm looking forward to hearing your comments.

EDIT: I tried it using David's answer and created my own IHttpHandler, but in there I don't get my desired requests and furthermore it is now stripping all JS-requests. Here is my web.config:

<add name="LocalizerHandler" path="*.js" verb="*" type="Website.Utility.LocalizerHttpHandler, Website" />

And here is my handler:

    class LocalizerHttpHandler : IHttpHandler
    {
        #region IHttpHandler Members

        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }

        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            Trace.WriteLine(string.Format("ProcessRequest: Req/Resp.: {0} - {1}", context.Request.ContentType, context.Response.ContentType));

            if (context.Request.ContentType.Contains("java") ||
                context.Response.ContentType.Contains("java"))
            {

            }
        }

        #endregion
    }

It only outputs the following on a page with a <script> tag:

ProcessRequest: Req/Resp.: - text/html

ProcessRequest: Req/Resp.: - text/html

ProcessRequest: Req/Resp.: - text/html

ProcessRequest: Req/Resp.: - text/html

ProcessRequest: Req/Resp.: - text/html

Do I miss anything here?

Community
  • 1
  • 1
Chris
  • 1
  • 2
  • The following SO post may be helpful: http://stackoverflow.com/questions/12732547/custom-http-handler-in-mvc-3-application -- or this one: http://stackoverflow.com/questions/5621391/serve-javascript-file-via-http-handler. In summary, I believe you want to create a custom `HttpHandler`. – David Tansey Nov 26 '14 at 17:34
  • Thanks David, that may look like what I needed. I'll try it out soon and let you know. – Chris Nov 26 '14 at 17:47
  • Unfortunately, I couldn't get it to work. See EDIT above. – Chris Nov 26 '14 at 18:23

0 Answers0