Is there an equivalent to “HttpContext.Response.Write” in Asp.Net Core 2?

前端 未结 3 889
滥情空心
滥情空心 2020-12-18 02:16

I\'m trying to append some HTML and Javascript content on page using ActionFilter in Asp.Net Core 2.

In MVC, it\'s working with



        
相关标签:
3条回答
  • 2020-12-18 02:26

    You can try something like this

    In a custom implementation of INopStartup.Configure(IApplicationBuilder application)

    application.Use(async (context, next) =>    
    {
        using (var customStream = new MemoryStream())
        {
            // Create a backup of the original response stream
            var backup = context.Response.Body;
    
            // Assign readable/writeable stream
            context.Response.Body = customStream;
    
            await next();
    
            // Restore the response stream
            context.Response.Body = backup;
    
            // Move to start and read response content
            customStream.Seek(0, SeekOrigin.Begin);
            var content = new StreamReader(customStream).ReadToEnd();
    
            // Write custom content to response
            await context.Response.WriteAsync(content);
        }
    });
    

    And than in your custom ResultFilterAttribute

    public class MyAttribute : ResultFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            try
            {
                var bytes = Encoding.UTF8.GetBytes("Foo Bar");
    
                // Seek to end
                context.HttpContext.Response.Body.Seek(context.HttpContext.Response.Body.Length, SeekOrigin.Begin);
                context.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
            }
            catch
            {
                // ignored
            }
    
            base.OnResultExecuted(context);
        }
    }
    

    And the result

    Hope this helps to get into the right way.

    0 讨论(0)
  • 2020-12-18 02:35

    Response.Body.Write takes a byte array as an argument.

    public void OnGet() {
        var text = "<h1>Hello, Response!</h1>";
        byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
        Response.Body.Write(data, 0, data.Length);
    }
    

    or async version:

    public async Task OnGetAsync() {
        var text = "<h1>Hello, Async Response!</h1>";
        byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
        await Response.Body.WriteAsync(data, 0, data.Length);
    }
    
    0 讨论(0)
  • 2020-12-18 02:39

    The static and asynchronous method HttpResponseWritingExtensions.WriteAsync is currently the preferred way of reaching this goal.

    Currently, you can find it in the assembly Assembly Microsoft.AspNetCore.Http.Abstractions.

    using Microsoft.AspNetCore.Http;
    
    [HttpGet("test")]
    public async Task GetTest()
        => await HttpResponseWritingExtensions.WriteAsync(this.Response, "Hello World");
    
    0 讨论(0)
提交回复
热议问题