Last active
December 28, 2017 13:04
-
-
Save GregorT/4070b2956932a1d0aaa7a3fc196b601d to your computer and use it in GitHub Desktop.
Converting IActionResult view to javascript file with custom ActionFilterAttribute in Asp.Net Core 2x
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
namespace yourApplicationNameSpace | |
{ | |
public class JavascriptOutputAttribute : ActionFilterAttribute | |
{ | |
private static readonly Regex OpenScriptTag = new Regex(@"^\s*<script[^>]*>", RegexOptions.Compiled); | |
private static readonly Regex CloseScriptTag = new Regex(@"</script>\s*$", RegexOptions.Compiled); | |
public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) | |
{ | |
var resp = context.HttpContext.Response; | |
using (var buffer = new MemoryStream()) | |
{ | |
var realBody = resp.Body; | |
context.HttpContext.Response.Body = buffer; | |
context.HttpContext.Response.ContentType = "text/javascript"; | |
await next(); | |
var newResponse = ReformatResponseToJavascriptFile(buffer); | |
using (var newResponseBuffer = new MemoryStream(Encoding.UTF8.GetBytes(newResponse))) | |
{ | |
resp.Body = realBody; | |
await newResponseBuffer.CopyToAsync(realBody); | |
} | |
} | |
} | |
private static string ReformatResponseToJavascriptFile(MemoryStream buffer) | |
{ | |
string response; | |
buffer.Seek(0, SeekOrigin.Begin); | |
using (var sr = new StreamReader(buffer)) | |
{ | |
response = sr.ReadToEnd(); | |
} | |
if (OpenScriptTag.IsMatch(response) && CloseScriptTag.IsMatch(response)) | |
{ | |
response = OpenScriptTag.Replace(response, string.Empty); | |
response = CloseScriptTag.Replace(response, string.Empty); | |
} | |
return response; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use it:
[JavascriptOutput]
public IActionResult MyDynamicJavascriptFile()
{
return View();
}