是否有等同于" HttpContext.Response.Write"在Asp.Net Core 2?

时间:2017-11-17 12:10:05

标签: nopcommerce httpcontext asp.net-core-2.0 nopcommerce-4.0

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

在MVC中,它正在使用

 filterContext.HttpContext.Response.Write(stringBuilder.ToString());

但在Core中它不起作用。

我试图用这个来实现:

filterContext.HttpContext.Response.WriteAsync(stringBuilder.ToString());

但它使完整页面变为空白。

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

3 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情

INopStartup.Configure(IApplicationBuilder应用程序)的自定义实现中

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);
    }
});

而不是您的自定义 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);
    }
}

结果

Result HTML

希望这有助于以正确的方式进行。

答案 1 :(得分:2)

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

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

using Microsoft.AspNetCore.Http;

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

答案 2 :(得分:1)

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);
}

或async版本:

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);
}