Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

but in Core it not working.

I tried to implement with this:

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

But it make complete page to blank.

I'm looking solution for nopCommerce 4.0 which build in Asp.Core 2.0

like image 216
Raju Paladiya Avatar asked Nov 17 '17 12:11

Raju Paladiya


People also ask

What is HttpContext in .NET core?

HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received. The HttpContext instance is accessible by middleware and app frameworks such as Web API controllers, Razor Pages, SignalR, gRPC, and more.

How do I get HttpContext in service?

In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.

What is HttpContext C#?

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.

What is System Web HttpContext current application?

HttpContext. Current. Application is simply a reference to the static global HttpApplicationState object in . NET for your Web Application, of which there should be one global instance per web application. By storing data there, you provide fast, thread-safe access to your global variables.


3 Answers

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

UPDATE 2022-02-23

A little bit related to the topic. Using the ASP.NET Core 6.0 you can write a simple response using Minimal API like this:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World");
app.Run();

Source: MSDN

like image 158
ˈvɔlə Avatar answered Sep 16 '22 11:09

ˈvɔlə


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);
}
like image 37
dragansr Avatar answered Sep 19 '22 11:09

dragansr


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

Result HTML

Hope this helps to get into the right way.

like image 40
Raphael Avatar answered Sep 20 '22 11:09

Raphael