Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Converting IActionResult view to javascript file with custom ActionFilterAttribute in Asp.Net Core 2x
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;
}
}
}
@GregorT

This comment has been minimized.

Copy link
Owner Author

@GregorT GregorT commented Dec 28, 2017

how to use it:

[JavascriptOutput]
public IActionResult MyDynamicJavascriptFile()
{
return View();
}

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