.net core小网关

a 夏天 提交于 2020-12-16 16:05:59

最近在做一个项目, .net core C#已经开发了大部分功能 接着的功能需要让JAVA来完成

所以需要处理URL透传,对URL地址拦截并请求JAVA编码的API

实现方式如下:

1、首页我们创建一个中间件对路由进行处理

public class GateWayMiddleware
    {
        private readonly RequestDelegate m_Next;
        private string URL;
        public ProxyMiddleware(RequestDelegate next)
        {
            this.m_Next = next;
        }

        public Task Invoke(HttpContext context)
        {
            //通过URL进行匹配第三方的URL地址
            URL = GetUrl(context.Request.Path);

            //如果未匹配到任何第三方的URL的地址,直接往管道正常流走
            if (string.IsNullOrEmpty(URL))
                return this.m_Next(context);

            //请求的GET方式处理
            if (context.Request.Method.ToUpper() == "GET")
                return this.HttpGet(context);

            //请求的GET方式处理
            if (context.Request.Method.ToUpper() == "POST")
                return this.HttpPost(context);

            //请求如果不是json格式处理
            if (context.Request.ContentType == null || context.Request.ContentType.IndexOf("application/json") < 0)
            {
                context.Response.StatusCode = 403;
                context.Response.ContentType += "application/json;charset=utf-8;";
                return context.Response.WriteAsync("Please set ContentType=application/json");
            }

            return null;
        }

        private Task HttpGet(HttpContext context)
        {
            Task task = new Task(() =>
            {
                string strQueryString = context.Request.QueryString.ToString();

                //该GET方式是 KeeSoft自带,获取远程URL地址内容
                string constResp =  KeeSoft.Core.HttpStream.HttpGet(URL + "?" + strQueryString);

                using (var strStream = new StreamWriter(context.Response.Body))
                {
                    strStream.Write(constResp);
                    strStream.Flush();
                }
            });
            task.Start();
            return task;
        }

        private Task HttpPost(HttpContext context)
        {
            Task task = new Task(() =>
            {
                long contentLen = context.Request.ContentLength == null ? 0 : context.Request.ContentLength.Value;

                byte[] buffer = new byte[contentLen];

                context.Request.Body.Read(buffer, 0, buffer.Length);

                string strQueryString = context.Request.QueryString.ToString();

                //该POST方式是 KeeSoft自带,获取远程URL地址内容
                string constResp = KeeSoft.Core.HttpStream.HttpPostJson(
                    URL + "?" + strQueryString, System.Text.Encoding.UTF8.GetString(buffer));

                using (var strStream = new StreamWriter(context.Response.Body))
                {
                    strStream.Write(constResp);
                    strStream.Flush();
                }
            });
            task.Start();
            return task;
        }

        /// <summary>
        /// 匹配配置文件的URL地址
        /// </summary>
        /// <param name="_url">当前的URL地址</param>
        /// <returns></returns>
        private string GetUrl(string _url)
        {
            var routes = GateWayProject.Instance;

            string strApiUrl = "";

            foreach (var m in routes.RoutesApi)
            {
                foreach (var s in m.url)
                {
                    if (s.Contains(_url))
                    {
                        strApiUrl = s;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(strApiUrl)) break;
            }

            return strApiUrl;
        }
    }

2、如果使用该中间件,在Startup.cs文件

public void ConfigureServices(IServiceCollection services)
        {
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("gateway.json");
            var config = builder.Build();

            GateWayProject.Instance = config.Get<GateWayProject>();

            services.AddMvc();
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder =>
            {
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowAnyOrigin();
            });

            app.UseMiddleware<GateWayMiddleware>();

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\"))
            });

            app.UseMvc();
        }

完成以上两步,小型的路由跳转就已经完成

下面是附上以上代码里出现的 

gateway.json //第三方URL地址配置

GateWayProject.cs //第三方URL解析的类

 

{
  "RoutesApi": [
    {
      "name": "KeeSoft",
      "url": [ "http://192.168.70.11:50399/api/tests" ]
    }
  ]
}
public class GateWayProject
    {
        public static GateWayProject Instance { get; set; }

        public RoutesApi[] RoutesApi { get; set; }
    }

    public class RoutesApi
    {
        public string name { get; set; }
        public string[] url { get; set; }
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!