zoukankan      html  css  js  c++  java
  • .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

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

  • 相关阅读:
    hadoopfs: 未找到命令...
    WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    centos 7 安装音乐播放器(亲测可用)(转载)
    Linux 脚本编写基础
    Zip加密
    Qt嵌入cef3关闭窗口时崩溃的问题
    C++11多线程基础
    C++11多线程(std::atomic)
    C++11多线程(thread_local)
    VS 新建RelWithDebInfo模式
  • 原文地址:https://www.cnblogs.com/xuzeyu/p/9400793.html
Copyright © 2011-2022 走看看