Skip to content

Instantly share code, notes, and snippets.

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
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);
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);
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));
Copy link

GregorT commented Dec 28, 2017

and this is for .Net Core 2x version:

have fun.

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