Add content to every view or component in ASP NET MVC

464 Views Asked by At

I'm using ASP .NET Core MVC (views and controllers).

Is there a way to add some additional output to all *.cshtml files using middleware, filter or something similar?

I would like to display the path(s) of all cshtml-files like the view itself, partial views, layout-file or components, that are part of the current page.

This is how it should look like: enter image description here

Right now, I have to add this line to the *.cshtml files, one by one:

@using WkOne.AuthorizationServer.ViewModels;
@model IEnumerable<UserViewModel>

@{
    Layout = "_Layout3Cols";
    ViewData["Title"] = "Users";
}

<!--  I need this line in every cshtml file                -->
<!--                      \                                -->
<div style="font-size: small;background-color: #CFC;">Path: @Path.ToString() </div> 


<table class="table">

<!-- ... and so on...                                     -->

But what I'm looking for is a way to do this in central place. Any suggestions?

1

There are 1 best solutions below

1
Ruikai Feng On

MVC project returns the html codes(razor codes has already been complied to html,so your codes shouldn't contain razor codes) which contained in response body to browser, The response body could write but couldn't be read ,if you want to add the html codes somewhere you want ,I think you need to replace the default body

I tried as below and added the text "hi"

 public class CusTestMiddleware
        {
            private readonly RequestDelegate _next;
    
            public CusTestMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task InvokeAsync(HttpContext context)
            {
                
                var response = context.Response;
                var responseOriginalBody = response.Body;
                using var memStream = new MemoryStream();
                response.Body = memStream;
                
                await _next(context);
    
                var targetstr = "<a>hi</a>";
                byte[] targetbyte = Encoding.UTF8.GetBytes(targetstr);            
                memStream.Write(targetbyte);
                memStream.Position = 0;
                var responseReader = new StreamReader(memStream);
                var responseBody = await responseReader.ReadToEndAsync();
                memStream.Position = 0;
                await memStream.CopyToAsync(responseOriginalBody);
                response.Body = responseOriginalBody;
            }
        }

enter image description here