In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to return a specific page in asp.net core middleware". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to return to a specific page in asp.net core middleware".
Preface
In asp.net core, there exists the concept of middleware. In middleware, we can intervene in the http request pipeline earlier than the filter, so as to realize the aspect processing of every http request and response, so as to achieve some special functions.
When using middleware, we often implement non-business requirements such as authentication, request logging, global exception handling, and so on. If you have used components such as swashbuckle (swagger), health check, mini profiler, etc., in asp.net core, you will find that these third-party components often provide pages that allow us to visually complete certain operations or browse certain data.
Step by Step
The final function is actually very simple. When the user jumps to a specified address, the custom middleware returns the specified page by matching to that path, so it mainly involves how the middleware is created and how to handle static file references in the page.
Because this piece will not contain a lot of code, so the main purpose here is to analyze the code of Swashbuckle.AspNetCore to understand how it implements this function, so as to provide an idea for our functional implementation.
When using Swashbuckle.AspNetCore in asp.net core, we usually need to configure the following components in the Startup class to generate a json file based on the information of the current program = "publicly generated json file address =" generate a visual interactive page based on the json file
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
twenty-six
twenty-seven
twenty-eight
twenty-nine
thirty
thirty-one
thirty-two
thirty-three
thirty-four
thirty-five
thirty-six
thirty-seven
thirty-eight
thirty-nine
Public class Startup
{
/ / This method gets called by the runtime. Use this method to add services to the container.
Public void ConfigureServices (IServiceCollection services)
{
/ / generate json file for swagger configuration
Services.AddSwaggerGen (s = >
{
S.SwaggerDoc ("v1", new OpenApiInfo
{
Contact = new OpenApiContact
{
Name = "Danvic Wang"
Url = new Uri ("https://yuiter.com"),
}
Description = "Template.API-ASP.NET Core backend interface template"
Title = "Template.API"
Version = "v1"
});
/ / Parameter uses the naming method of hump
S.DescribeAllParametersInCamelCase ()
});
}
/ / This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Public void Configure (IApplicationBuilder app, IWebHostEnvironment env)
{
/ / expose the json file nodes generated by swagger
App.UseSwagger ()
/ / enable swagger visual interactive page
App.UseSwaggerUI (s = >
{
S.SwaggerEndpoint ($"/ swagger/v1/swagger.json"
$"Swagger doc v1")
});
}
}
You can see that the final page presented to the user is actually done by calling the UseSwaggerUI method in the Configure method, which is in the Swashbuckle.AspNetCore.SwaggerUI assembly, so here you can find the corresponding folder directly from the github and the source code under clone to see how to return a specific page in the middleware.
In the code under clone, excluding some project files used by c # and node.js, we can see that the files in the whole project can be divided into three parts according to their functions, of which the core is in the SwaggerUIMiddleware class, so here we mainly focus on the implementation of this middleware class.
In an asp.net core middleware, the core processing logic is in the Invoke/InvokeAsync method. Combined with the scenario when we use swagger, we can see that there are two main processing logic when presenting the pages contained in the component to the user.
1. When matching the user's access to / swagger, the http status code of 301 is returned, and the browser is redirected to / swagger/index.html, thus triggering the execution of the middleware again.
2. When the address matching to the request is / swagger/index.html, the file embedded in the assembly is obtained in the form of stream stream, converted into a string, and then the response type of the request is specified as text/html, so that the page is returned to the user.
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
Public async Task Invoke (HttpContext httpContext)
{
Var httpMethod = httpContext.Request.Method
Var path = httpContext.Request.Path.Value
/ / If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
If (httpMethod = = "GET" & & Regex.IsMatch (path, $"^ /? {Regex.Escape (_ options.RoutePrefix)} /? $"))
{
/ / Use relative redirect to support proxy environments
Var relativeRedirectPath = path.EndsWith ("/")
? "index.html"
: $"{path.Split ('/') .Last ()} / index.html"
RespondWithRedirect (httpContext.Response, relativeRedirectPath)
Return
}
If (httpMethod = = "GET" & & Regex.IsMatch (path, $"^ / {Regex.Escape (_ options.RoutePrefix)} /? index.html$"))
{
Await RespondWithIndexHtml (httpContext.Response)
Return
}
Await _ staticFileMiddleware.Invoke (httpContext)
}
It should be noted here that because similar to this function, we may package it into a separate nuget package and then reference it through nuget, so in order to correctly get the page and the static resource files it uses, we need to modify the properties of these static files to embedded resources so that they can be included in the assembly when packaged.
For web pages, there is a relative path relationship when referencing these static resource files, so here, in the constructor of middleware, we need to map the static files that the page needs to use under the same / swagger path as the web page by building StaticFileMiddleware middleware, so as to ensure that the resources needed by the page can be loaded correctly.
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
twenty-six
twenty-seven
twenty-eight
twenty-nine
thirty
thirty-one
thirty-two
thirty-three
Public class SwaggerUIMiddleware
{
Private const string EmbeddedFileNamespace = "Swashbuckle.AspNetCore.SwaggerUI.node_modules.swagger_ui_dist"
Private readonly SwaggerUIOptions _ options
Private readonly StaticFileMiddleware _ staticFileMiddleware
Public SwaggerUIMiddleware (
RequestDelegate next
IHostingEnvironment hostingEnv
ILoggerFactory loggerFactory
SwaggerUIOptions options)
{
_ options = options? New SwaggerUIOptions ()
_ staticFileMiddleware = CreateStaticFileMiddleware (next, hostingEnv, loggerFactory, options)
}
Private StaticFileMiddleware CreateStaticFileMiddleware (
RequestDelegate next
IHostingEnvironment hostingEnv
ILoggerFactory loggerFactory
SwaggerUIOptions options)
{
Var staticFileOptions = new StaticFileOptions
{
RequestPath = string.IsNullOrEmpty (options.RoutePrefix)? String.Empty: $"/ {options.RoutePrefix}"
FileProvider = new EmbeddedFileProvider (typeof (SwaggerUIMiddleware). GetTypeInfo (). Assembly, EmbeddedFileNamespace)
}
Return new StaticFileMiddleware (next, hostingEnv, Options.Create (staticFileOptions), loggerFactory)
}
}
When the rendering of the page is finished, because we usually create a separate class library to implement these functions, the page may include the data interaction between the front and back ends. Since we have finished setting the routing rules in the host API project, we only need to reference Microsoft.AspNetCore.Mvc.Core through nuget in the class library, and then define controller like Web API. Make sure that the middleware can be called after the route matching rule by the host program.
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
Public void Configure (IApplicationBuilder app, IWebHostEnvironment env)
{
If (env.IsDevelopment ())
{
App.UseDeveloperExceptionPage ()
}
App.UseHttpsRedirection ()
App.UseRouting ()
App.UseAuthorization ()
/ / Endpoint routing rule setting
App.UseEndpoints (endpoints = >
{
Endpoints.MapControllers ()
});
/ / Custom middleware
App.UseMiddleware ()
}
Thank you for your reading, the above is the content of "how to return a specific page in asp.net core middleware", after the study of this article, I believe you have a deeper understanding of how to return a specific page in asp.net core middleware, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.