在Asp.Net Core 2中是否有等效于“ HttpContext.Response.Write”的文件?

Raj*_*iya 5 httpcontext nopcommerce asp.net-core-2.0 nopcommerce-4.0

我正在尝试使用Asp.Net Core 2中的ActionFilter在页面上附加一些HTML和Javascript内容。

在MVC中,它与

 filterContext.HttpContext.Response.Write(stringBuilder.ToString());
Run Code Online (Sandbox Code Playgroud)

但是在Core中它不起作用。

我试图用这个实现:

filterContext.HttpContext.Response.WriteAsync(stringBuilder.ToString());
Run Code Online (Sandbox Code Playgroud)

但这会使整个页面空白。

我正在寻找内置在Asp.Core 2.0中的nopCommerce 4.0的解决方案

dra*_*nsr 7

Response.Body.Write 将字节数组作为参数。

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

或异步版本:

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);
}
Run Code Online (Sandbox Code Playgroud)


WoI*_*IIe 5

当前,静态和异步方法HttpResponseWritingExtensions.WriteAsync是实现此目标的首选方法。

当前,您可以在Assembly Assembly中找到它Microsoft.AspNetCore.Http.Abstractions

using Microsoft.AspNetCore.Http;

[HttpGet("test")]
public async Task GetTest()
    => await HttpResponseWritingExtensions.WriteAsync(this.Response, "Hello World");
Run Code Online (Sandbox Code Playgroud)


Rap*_*ael 4

你可以尝试这样的事情

在自定义实现中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);
    }
});
Run Code Online (Sandbox Code Playgroud)

然后按照您的习惯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);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果

结果 HTML