Skip to content

Instantly share code, notes, and snippets.

@mariusschulz
Last active April 16, 2020 15:24
Show Gist options
  • Save mariusschulz/6028061 to your computer and use it in GitHub Desktop.
Save mariusschulz/6028061 to your computer and use it in GitHub Desktop.
Here's the ExternalJavaScriptFileAttribute that I showed in my blog post "Generating External JavaScript Files Using Partial Razor Views" (see http://blog.mariusschulz.com/generating-external-javascript-files-using-partial-razor-views).
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 = "text/javascript";
}
private class StripEnclosingScriptTagsFilter : MemoryStream
{
private static readonly Regex LeadingOpeningScriptTag;
private static readonly Regex TrailingClosingScriptTag;
private readonly StringBuilder _output;
private readonly Stream _responseStream;
static StripEnclosingScriptTagsFilter()
{
LeadingOpeningScriptTag = new Regex(@"^\s*<script[^>]*>", RegexOptions.Compiled);
TrailingClosingScriptTag = new Regex(@"</script>\s*$", RegexOptions.Compiled);
}
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();
if (LeadingOpeningScriptTag.IsMatch(response) && TrailingClosingScriptTag.IsMatch(response))
{
response = LeadingOpeningScriptTag.Replace(response, string.Empty);
response = TrailingClosingScriptTag.Replace(response, string.Empty);
}
WriteStringResponse(response);
_output.Clear();
}
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(responseData);
}
private void WriteStringResponse(string response)
{
byte[] outdata = Encoding.Default.GetBytes(response);
_responseStream.Write(outdata, 0, outdata.GetLength(0));
}
}
}
}
@melgish
Copy link

melgish commented May 8, 2015

Should line 63 be converting the buffer or responseData ?

@GregorT
Copy link

GregorT commented Dec 28, 2017

and this is for .Net Core 2x version:
https://gist.github.com/GregorT/4070b2956932a1d0aaa7a3fc196b601d

have fun.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment