0

I'm porting an ASP.NET HTTP handler to an ASP.NET Core middleware class. The majority of the time, the handler responds with a simple UTF-8 text response. Sometimes, the HTTP handler would stuff a big object graph in the ASP.NET Session state, then do a Response.Redirect to an ASPX Web Form page. The web form page extracts the object graph from the Session state and renders it.

It seems to me that the redirection is unnecessary, plus it forces me to include session state in my application, which I don't want. What I do want is to translate the Web Forms page to a Razor page, and then somehow invoke the Razor page directly to render my object graph. Can my middleware in essence yield control to Razor, specifying: "here is the cshtml page I want you to render and here is a object graph?"

I can easily create PageModel class with a property ObjectGraph, but how do I yield over control to Razor to render that cshtml page?

   public async Task Invoke(HttpContext ctx) {
       var objectGraph = ComputeObjectGraph(ctx.Request);
       if (IsSimpleRendering(ctx.Request)) {
           async DoSimpleRendering(objectGraph, ctx.Response);
       } else {
           var razorPageModel = new HtmlRendererModel(objectGraph);
           // TODO: hand off to Razor, using "htmlrenderer.cshtml" as a template.
           // async DoHtmlRendering("htmlrenderer.cshtml", razorPageModel, ctx);
       }
    }
John Källén
  • 7,551
  • 31
  • 64
  • 1
    Once the View is rendered, what do you want to do from there? Do you need it returned as a `Partial View` or a `string`? Since you mentioned returning UTF-8 text, I'm guessing you want to turn a Razor view into a string, so check this out - [how-to-render-an-asp-net-mvc-view-as-a-string](https://stackoverflow.com/questions/483091/how-to-render-an-asp-net-mvc-view-as-a-string) – Ryan Wilson Apr 15 '21 at 12:28
  • @RyanWilson: Ideally I want the View to render directly to the `Response` object the middleware obtains from its `HttpContext` parameter. The middleware just gets out of the way and does no further processing. – John Källén Apr 15 '21 at 13:06
  • You can get the middleware to construct the model, serialise it and add it to HttpContext.Items, then you can retrieve that in the Razor Page. – Mike Brind Apr 15 '21 at 13:09
  • I'd like to avoid serializing the model, but rather have an instance of the PageModel be consumed by the razor engine, and having it output the results directly to Context.Response without intermiate conversions to strings. The object graph can be quite large. – John Källén Apr 15 '21 at 15:20

0 Answers0