.net Core 简单中间件使用
在项目文件夹中定义一个 Middleware 文件夹,建一个中间件类
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebOclot { // 定义一个中间件类型 public class UserValidate { private RequestDelegate _next; public UserValidate(RequestDelegate next) { _next = next; // 下一个中间件 } public async Task InvokeAsync(HttpContext context) { string method = context.Request.Method; string userName = ""; string Pwd = ""; if (method == "GET") { userName = context.Request.Query["UserName"]; Pwd = context.Request.Query["Pwd"]; } else if (method == "POST") { userName = context.Request.Form["UserName"]; Pwd = context.Request.Form["Pwd"]; } if (userName == "zs" && Pwd == "123") // 验证是否通过 { await _next(context); // 往下执行 } else { await context.Response.WriteAsync("用户名或密码不正确"); } } } }
注册中间件
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Ocelot.DependencyInjection; using Ocelot.Middleware; using Ocelot.Provider.Consul; using Ocelot.Provider.Polly; namespace WebOclot { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddOcelot().AddConsul().AddPolly(); // 删除掉此处所有默认的配置 } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMiddleware<UserValidate>(); app.UseOcelot(); // 删除掉此处所有默认的配置 } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!