私たちは、asp.net内のすべての要求は、順番にパイプラインの一連のイベントをトリガーする要求パイプライン、を経ることを知っています。その後、我々は、ミドルウェアコンポーネントを理解することができる要求パイプラインであり、私たちの要求と応答の処理を容易にするために、要求を傍受するために使用することができ、ミドルウェアは、複数定義することができ、パイプライン内の各ブローカは要求することができます傍受、それは次のミドルウェアへの転送を要求するかどうかを決定することができます。
カスタムミドルウェア
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace dnc
{
public class RequestMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<RequestMiddleware>();
}
public Task Invoke(HttpContext httpContext)
{
_logger.LogInformation($"Path:{ httpContext.Request.Path }");
_logger.LogInformation($"Client Ip:{httpContext.Connection.RemoteIpAddress.ToString()}");
return _next(httpContext);
}
}
}
拡張メソッドを追加します。
namespace dnc
{
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseReq(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestMiddleware>();
}
}
}
でstartup.cs
有効ミドルウェア
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseReq();
// 使用MVC
app.UseMvc();
}