.net Core中间件实战

   新建一个ASP.NET Core Web Application 项目选中空模板

image.png

image.png

 

然后为项目添加一个Microsoft.Extensions.Logging.Console

image.png

由于我用的.net core1.1 则选择对应1.1版本

 

添加好了以后新建一个类RequestIPMiddleware.cs

 

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xzyCore
{ 
  public class RequestIPMiddleware  
  {       
    private readonly RequestDelegate _next;
          
    private readonly ILogger _logger;
         
    public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) {
        _next = next;
        _logger =loggerFactory.CreateLogger<RequestIPMiddleware>();
    }
         
    public async Task Invoke(HttpContext context) {      
        _logger.LogInformation("User IP:" + context.Connection.RemoteIpAddress.ToString());
        await _next.Invoke(context);
    } 
  }
}

 

  然后在创建一个RequestIPExtensions.cs

using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xzyCore
{
  public static class RequestIPExtensions  
  {       
    public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder) {
        return builder.UseMiddleware<RequestIPMiddleware>();      
    } 
  }
}

这样就编写好一个中间件了。

在Startup.cs中添加app.UseRequestIP();

 // This method gets called by the runtime. Use this
method to configure the HTTP request pipeline.   
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)     
{
            loggerFactory.AddConsole();
            app.UseRequestIP();
            if(env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            } 
            app.Run(async (context) =>
            {
               await context.Response.WriteAsync("Hello
World!");
            });
}

然后在运行程序

image.png

成功运行,这里我们还可以对这个中间件进行进一步改进,增加更多的功能,如限制访问等。

 

转载于:https://www.cnblogs.com/xuzeyu/p/9400793.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值