asp论坛回复功能怎么实现_在asp.netcore中使用中间件(middleware)实现api拦截及验证功能
本文只对api接口,header请求参数进行简单验证,起到抛砖引玉使用,需要深入验证,请自行扩展
项目目录结构如图
- 中间件类
using ApiMiddleware.Common.DataEnityModel;using ApiMiddleware.Common.DbContext;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Primitives;using Newtonsoft.Json;using System;using System.Diagnostics;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ApiMiddleware.Middleware{ public class RequestHeaderVerificationMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; /// /// 计时器 /// private Stopwatch _stopwatch; private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms"; public RequestHeaderVerificationMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context, MySqlMasterDbContext masterDbContext) { _stopwatch = new Stopwatch(); _stopwatch.Start(); _logger.LogError($"Handling request: {context.Request.Path}"); if (!context.Request.Headers.TryGetValue("request_id", out StringValues request_id) || string.IsNullOrEmpty(request_id)) { await HandleMessage(context, JsonConvert.SerializeObject(new { msg = "request_id不可为空", request_id = request_id })); goto step; } if (!context.Request.Headers.TryGetValue("uname", out StringValues uname) || string.IsNullOrEmpty(uname)) { await HandleMessage(context, JsonConvert.SerializeObject(new { msg = "名称不可为空", request_id = request_id, uname = uname })); goto step; } var stu = new student { id = request_id, stu_name = uname, createtime = DateTime.Now, updatetime = DateTime.Now }; var model = masterDbContext.student.FirstOrDefault(m => m.id == request_id); if (model == null) masterDbContext.Add(stu); else { model.stu_name = uname; model.updatetime = DateTime.Now; masterDbContext.Update(model); } masterDbContext.SaveChanges(); context.Response.OnStarting(() => { // Stop the timer information and calculate the time _stopwatch.Stop(); var responseTimeForCompleteRequest = _stopwatch.ElapsedMilliseconds; // Add the Response time information in the Response headers. context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString(); return Task.CompletedTask; }); step: if (!context.Response.HasStarted) { await _next(context); } } /// /// 错误信息或验证信息处理方法 /// /// /// /// private async Task HandleMessage(HttpContext context, string msg) { context.Response.ContentType = "text/json;charset=utf-8;"; //浏览器在开发环境显示详细错误信息,其他环境隐藏错误信息 await context.Response.WriteAsync(msg); } }}
using Microsoft.AspNetCore.Builder;namespace ApiMiddleware.Middleware{ public static class MyMiddlewareExtensions { public static void UseMyMiddleware(this IApplicationBuilder builder) { builder.UseMiddleware(); } }}
- 数据库操作类MySqlMasterDbContext
using ApiMiddleware.Common.DataEnityModel;using Microsoft.EntityFrameworkCore;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace ApiMiddleware.Common.DbContext{ public class MySqlMasterDbContext : Microsoft.EntityFrameworkCore.DbContext { private string _conn; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!string.IsNullOrEmpty(_conn)) { optionsBuilder.UseMySQL(_conn); } base.OnConfiguring(optionsBuilder); } public MySqlMasterDbContext(DbContextOptions options) : base(options) { Database.EnsureCreated(); } public MySqlMasterDbContext(string conn) { _conn = conn; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } public DbSet student { get; set; } }}
- 在Startup中注册中间件
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using ApiMiddleware.Common.DbContext;using ApiMiddleware.Middleware;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.HttpsPolicy;using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Options;namespace ApiMiddleware{ 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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); var identityConn = "Server=localhost;Database=business;Uid=root;Pwd=root;"; services.AddDbContext(options => options.UseMySQL(identityConn)); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseMyMiddleware();//注册中间件 app.UseHttpsRedirection(); app.UseMvc(); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using ApiMiddleware.Common.DataEnityModel;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Newtonsoft.Json;namespace ApiMiddleware.Controllers{ [Route("api/[controller]")] [ApiController] public class StuController : ControllerBase { [HttpPost("stuinfo")] public ActionResult AddStu([FromBody]StudentExternal info) { return JsonConvert.SerializeObject(new { result="Success",Data=info.data}); } }}
- 请求实例测试,注意请求头不要带汉字,否则报错
- 如请求头带汉字,则报如下提示
asp论坛回复功能怎么实现_在asp.netcore中使用中间件(middleware)实现api拦截及验证功能相关推荐
- asp论坛回复功能怎么实现_微信公众号整合群发图文消息功能怎么实现?
对于微信公众号整合区分图文消息功能的实现,微号帮平台提供了服务号每月400次群发功能实现,公众平台提供了接口编程开发实现功能,均能达到微信公众号群发图文消息的功能效果,实现订阅号每天群发1次消息,服务 ...
- javascript编写_如何在JavaScript中使用解构来编写更简洁,功能更强大的代码
javascript编写 by Ashay Mandwarya ?️?? 由Ashay Mandwarya提供吗? 如何在JavaScript中使用解构来编写更简洁,功能更强大的代码 (How to ...
- 美图手机投射功能在哪_在Java 8中进行投射(还有其他功能?)
美图手机投射功能在哪 将实例转换为设计不良的类型. 尽管如此,在某些情况下没有其他选择. 从第一天开始,执行此功能就已成为Java的一部分. 我认为Java 8提出了对这种古老技术稍加改进的需求. 静 ...
- asp 调用java文件上传_用asp实现文件浏览、上传、下载的程序
可以放在服务器上,对服务器上的文件进行浏览.上传.下载,可下载文件源码. 把下所有代码入在一个文件里即可,文件的后缀要为asp. thedir = request("thedir" ...
- asp连接mysql数据库增删查_【ASP】ASP对Access数据库的连接、增删改查及ASP的基本语法...
本文讨论的是ASP,而不是Visual Studio写出来的.ASPX也就是ASP.NET. ASP不需要任何插件的支持,关键你是配置好WINDOWS的IIS服务器,把页面扔在上面执行就可以了. 不同 ...
- ipad分屏功能怎么用_微信支付分有什么用怎么涨分 支付分用途功能提升方法
[闽南网] 最近,许多用户都在好奇微信支付分是干什么的.许多用户都想知道微信中的支付分有什么用,下面文章小编将为大家介绍微信支付分的用途功能和提升方法. PS:还未开通的朋友请看这条攻略. 微信支付分 ...
- ipad分屏功能怎么开启_手机学习办公效率低?试试开启vivo“分屏多任务”功能...
在当下这个特殊时期,许多企业与学校纷纷选择在家办公/学习,诚然,在科技如此发达的今天,大众仅需一台手机,就可以完成大部分的工作与学习计划.但对于部分人群来说,手机每次只能显示一个应用的设定也拖慢了工作 ...
- 一个遮罩层怎么遮罩两个图层_premiere遮罩功能在哪儿_怎么在视频中加遮罩图层_遮罩图层制作教程详解...
premiere是一款非常受大众喜爱的视频剪辑神器.有时候为了给在pr软件中剪辑的视频做一些遮罩的动画,你可能会到ps中画出形状然后填充黑色或者白色,然后在导入pr软件中做动画使用.这样不免有些繁琐了 ...
- php手机号码一分钟发送一次短信_如何实现php手机短信验证功能
现在网站在建设网站时为了保证用户信息的真实性,往往会选择发短信给用户手机发验证码信息,只有通过验证的用户才可以注册,这样保证了用户的联系信息资料的100%的准确性 .今天笔者就跟大家分享一下如何实现p ...
最新文章
- Codeforces Round #547 (Div. 3) D
- Codeforces - 706B - Interesting drink - 二分 - 简单dp
- 2018北大计算机复试线,2018年北京大学考研复试分数线已公布
- cat testEOF,more
- AtCoder Grand Contest 004 C - AND Grid(思路题)
- Android PackageManager 详解
- 人口matlab数学模型,基于MATLAB构建人口数学模型研究二胎开放对中国人口的影响...
- 通过IP地址进行精准定位
- 什么是SFP光模块?
- windows 剪贴板监控
- Java 过滤器Url通配符处理
- U盘安装Ubuntu16.04报unable to find a medium containing a live file system和ACPI Error错误
- Sparkling Logic SMARTS 实时决策分析模块介绍
- HDFS的读写流程步骤(附图文解析)
- 2022年了,你还没搞清楚箭头函数与普通函数的区别嘛?
- 编译OpenArkCompiler出现进程被kil
- pycharm关联hadoop开发
- Matlab调用ANSYS的三种方法
- 学会这4个PPT技巧,你就能做出漂亮的PPT教学课件
- STM32F103RBT6型号说明及特征;
热门文章
- 用VLC读取摄像头产生RTSP流,DSS主动取流转发(一)
- LIS(最大上升子序列)
- Hive记录-配置远程连接(JAVA/beeline)
- 解决cookie跨域访问
- python学习第十节(yield表达式的应用+内置函数)
- IPSEC造成网络Destination host unreachable
- C#集合类(HashTable, Dictionary, ArrayList)与HashTable线程安全
- *27.硬实时和软实时
- 计算机视觉与深度学习,看这本书就够了
- oracle的存储过程 替换,为什么在存储过程中,变量替换无法使用索引?