Forked from mariusschulz/ExternalJavaScriptFileAttribute.cs
Last active
August 29, 2015 14:09
-
-
Save bencoderer/2f6bd131c8574238e759 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.IO; | |
| using System.Text; | |
| using System.Text.RegularExpressions; | |
| using System.Web.Mvc; | |
| namespace DemoApp | |
| { | |
| public class ExternalJavaScriptFileAttribute : ActionFilterAttribute | |
| { | |
| public override void OnResultExecuted(ResultExecutedContext filterContext) | |
| { | |
| var response = filterContext.HttpContext.Response; | |
| response.Filter = new StripEnclosingScriptTagsFilter(response.Filter); | |
| response.ContentType = "application/javascript"; | |
| } | |
| private class StripEnclosingScriptTagsFilter : MemoryStream | |
| { | |
| private const string Pattern = @"^<script[^>]*>(.*)</script>$"; | |
| private readonly Stream _responseStream; | |
| private readonly StringBuilder _output; | |
| public StripEnclosingScriptTagsFilter(Stream responseStream) | |
| { | |
| _responseStream = responseStream; | |
| _output = new StringBuilder(); | |
| } | |
| public override void Write(byte[] buffer, int offset, int count) | |
| { | |
| string response = GetStringResponse(buffer, offset, count); | |
| _output.Append(response); | |
| } | |
| public override void Flush() | |
| { | |
| string response = _output.ToString().Trim(); | |
| response = Regex.Replace(response, Pattern, "$1", RegexOptions.Singleline); | |
| WriteStringResponse(response); | |
| } | |
| private static string GetStringResponse(byte[] buffer, int offset, int count) | |
| { | |
| byte[] responseData = new byte[count]; | |
| Buffer.BlockCopy(buffer, offset, responseData, 0, count); | |
| return Encoding.Default.GetString(buffer); | |
| } | |
| private void WriteStringResponse(string response) | |
| { | |
| byte[] outdata = Encoding.Default.GetBytes(response); | |
| _responseStream.Write(outdata, 0, outdata.GetLength(0)); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment