How can I get a view as string in middleware?

melon NG 291 Reputation points
2022-02-13T23:03:22.613+00:00

In the middleware I want to return the content of a view (Not redirect to it).

In my opinion, I should use the

context.Response.WriteAsync();

to achieve it.

Now I need to get the html string of the view (Also work with Localizer/Model/ViewData in the view).

It seems there is not any tutorial about this. How can I solve it? Thank you.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,502 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,141 Reputation points Microsoft Vendor
    2022-02-16T08:21:43.79+00:00

    Hi @melon NG ,

    I want to create a custom 404 page without the app.UseStatusCodePages.

    To this issue, you can check Response.StatusCode in the Program.cs file (asp.net 6) or Startup.cs file (< asp.net 5), then return custom 404 error message or set the path of the custom error page. For example: if meet the 404 error, change the app.UseStatusCodePages(); as below:

    //app.UseStatusCodePages();  
      
    app.Use(async (context, next) =>  
    {  
        await next();  
        if (context.Response.StatusCode == 404)  
        {   
            await context.Response.WriteAsync("404 not found!");  
            // you can also use the following code to set the path of the custom error page.  
            //context.Request.Path = "/Home/Custom404Error";  
            //await next();  
        }  
    });  
    

    The result as below:

    174878-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


2 additional answers

Sort by: Most helpful
  1. AgaveJoe 28,031 Reputation points
    2022-02-14T12:56:51.59+00:00

    Your design does not make a lot of sense which is the reason you cannot find any information. In MVC the view engine is responsible for rendering the Razor content into HTML. The results are passed back through middleware.

    Perhaps you want to log the response or you want to create a custom view engine? Can you explain the use case?


  2. Bruce (SqlWork.com) 63,741 Reputation points
    2022-02-14T17:05:43.837+00:00

    the trick is to register your middleware first. then it can pass a memory stream to the next, and harvest after. simple example:

    https://exceptionnotfound.net/using-middleware-to-log-requests-and-responses-in-asp-net-core/


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.