.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();
            // 刪除掉此處所有默認的配置
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章