日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

asp论坛回复功能怎么实现_在asp.netcore中使用中间件(middleware)实现api拦截及验证功能

發布時間:2025/4/16 asp.net 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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}); } }}
  • 請求實例測試,注意請求頭不要帶漢字,否則報錯
  • 如請求頭帶漢字,則報如下提示
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的asp论坛回复功能怎么实现_在asp.netcore中使用中间件(middleware)实现api拦截及验证功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。