Last active
April 16, 2020 15:24
-
-
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).
This file contains 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 = "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)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
and this is for .Net Core 2x version:
https://gist.github.com/GregorT/4070b2956932a1d0aaa7a3fc196b601d
have fun.