Middleware and Service
Contents
The purpose of the ASP.NET Core platform is to receive HTTP requests and send reposes to them,which ASP.NET Core delegates to middleware components. Middleware component are arranged in a chain,known as the request pipeline.
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,ILogger<Startup> logger)
{
logger.LogInformation("开始记录。。。。");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.Use(next =>
{
return async httpContext =>
{
if (httpContext.Request.Path.StartsWithSegments("/first"))
{
logger.LogInformation("开始记录1。。。。");
await httpContext.Response.WriteAsync("First!!!");
}
else
{
logger.LogInformation("开始记录2。。。。");
await next(httpContext);
}
};
});
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
logger.LogInformation("开始记录3。。。。");
await context.Response.WriteAsync("Hello World!");
});
});
}
}
可以在ConfigureServices(IServiceCollection services)中配置注册服务
– services.AddMvc();
添加MVC服务
可以在public void Configure(IApplicationBuilder app, IWebHostEnvironment env)中配置中间件,以及注入日志等
IWebHostEnvironment env可以获取当前的环境是开发环境还是生产环境还是预览演示环境
– app.UseWelcomePage()
显示欢迎页
– app.use()
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
public delegate Task RequestDelegate(HttpContext context);
app.Use(next =>
{
return async httpContext =>
{
if (httpContext.Request.Path.StartsWithSegments("/first"))
{
await httpContext.Response.WriteAsync("First!!!");
}
else
{
await next(httpContext);
}
};
});
- app.UseDeveloperExceptionPage();
会显示异常页面,要放在管道中比较靠前的位置 - app.useDefaultFiles()
可以使用该中间件设置指定的默认文件,然后将默认的文件在通过appUseStaticFiles() 返回,所以中间件的顺序很重要 - app.UseStaticFiles()
使用wwwroot中的静态页面或文件 - app.UseFileServer()
包含上面两个中间件功能,还可以包含目录浏览功能 - app.UseMvcWithDefaultRoute()
使用默认路由的MVC中间件
创建自定义中间件
app.Use(async (context,next)=>{
if(context.Request.Method==HttpMethods.Get && context.Request.Query["custom"]=="true"){
context.Reponse.ContextType="text/plain";
await context.Response.WriteAsync("Custom Middleware \n");
}
await next();
});
创建自定义类中间件
namespace Platform
{
public class QueryStringMiddleWare
{
private RequestDelegate next;
public QueryStringMiddleWare(RequestDelegate nextDelegate)
{
next=nextDelegate;
}
public async Task Invoke(HttpContext context)
{
if(context.Request.Method==HttpMethods.Get && context.Request.Query["custom"]=="true")
{
if(!context.Response.HasStarted)
{
context.Response.ContentType="text/plain";
}
await context.Response.WriteAsync("Class-based Middleware \n");
}
await next(context);
}
}
}
````
## 使用类中间件
```CSharp
app.UseMiddleware<Platform.QueryStringMiddleWare>();
Understanding the Return Pipeline Path
app.Use(async (context,next)=>{
await next();
await context.Response.WriteAsync($"\n Status Code:{context.Response.StatusCode}");
});
Useful HttpContext Members
Name | Descirption |
---|---|
Connection | This property returns a ConnectionInfo object that provides information about the network connection underlying the HTTP request,including details of local and remote IP address and ports |
Request | This property returns an HttpResponse object that is used to create a response to the HTTP request |
Session | This property returns the session data associated with the request. |
User | This property returns details of the user associated with the request |
Features | This property provides access to request features,which allow access to the low-level aspects of request handing |
Useful HttpRequest Members
Name | Description |
---|---|
Body | This property returns a stream that can be used to read the request body |
ContentLength | returns the value of the Content-Length header |
ContentType | return the value of the content-Type header |
Cookies | returns the request cookies |
Form | returns a representation of the request body as a form |
Headers | return the request headers |
IsHttps | returns true if the request was made using HTTPS |
Method | returns the HTTP verb-also known as the HTTP method-used for the request |
Path | returns the path section of the request URL |
Query | returns the query string section of the request URL as key-value pairs |
Useful HttpResponse Members
Name | Description |
---|---|
contentLength | sets the value of the Content-Length header |
ContentType | sets the value of the Content-Type header |
Cookies | allows cookies to be associated with the request |
HasStarted | returns true if ASP.NET Core has started to send the response headers to the client,after which it is not possible to make changes to the status code or headers |
Headers | allows the response headers to be set |
StatusCode | sets the status code for the response |
WriteAsync(data) | this asynchronous method writes a data string to the response body |
Redirect(url) | sends a redirection response |
short circuiting the request pipeline
Creating Pipeline Branches
Services
Services are object that provide features in a web application.Any calss can be used as a service.they are managed by ASP.NET Core,and a feature called dependency injection makes it possible to easily access service anywhere
middleware components use only the services they require to do theri work.
Filed under: ASP.NET Core,C#,编程 - @ 2022年4月9日 下午12:38