欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.netcore2.1 使用middleware对api请求头进行验证

程序员文章站 2022-06-01 17:02:12
本文只对api接口,header请求参数进行简单验证,起到抛砖引玉使用,需要深入验证,请自行扩展 项目目录结构如图 中间件类 using ApiMiddleware.Common.DataEnityModel; using ApiMiddleware.Common.DbContext; using ......

  本文只对api接口,header请求参数进行简单验证,起到抛砖引玉使用,需要深入验证,请自行扩展

  项目目录结构如图

.netcore2.1  使用middleware对api请求头进行验证

  •   中间件类
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;

        /// <summary>
        /// 计时器
        /// </summary>
        private stopwatch _stopwatch;
        private const string response_header_response_time = "x-response-time-ms";

        public requestheaderverificationmiddleware(requestdelegate next, ilogger<requestheaderverificationmiddleware> 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);
            }
        }


        /// <summary>
        /// 错误信息或验证信息处理方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        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<requestheaderverificationmiddleware>();
        }
    }
}

 

  • 数据库操作类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<mysqlmasterdbcontext> options) : base(options)
        {
            database.ensurecreated();
        }

        public mysqlmasterdbcontext(string conn)
        {
            _conn = conn;
        }
        protected override void onmodelcreating(modelbuilder builder)
        {
            base.onmodelcreating(builder);
        }



        public dbset<student> 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<mysqlmasterdbcontext>(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<string> addstu([frombody]studentexternal info)
        {
            return  jsonconvert.serializeobject(new { result="success",data=info.data});
        }
    }
}

 

  • 请求实例测试,注意请求头不要带汉字,否则报错

.netcore2.1  使用middleware对api请求头进行验证.netcore2.1  使用middleware对api请求头进行验证

  • 如请求头带汉字,则报如下提示

.netcore2.1  使用middleware对api请求头进行验证