ASP.NET Core 奇技淫巧之接口代理转发的实现
前言
先讲讲本文的开发背景吧..
在如今前后端分离的大背景下,咱的客户又有要求啦~
要前后端分离~ 然因为种种原因..没办法用用纯前端的框架(其实是学习成本高,又没钱请前端开发人员)...
所以最终决定了一种方案..
那就是采用mvc(只处理前端视图层,单纯是为了托管在.net core上)+webapi的方式来实现前后端分离(讲真,很奇葩)..
那么问题就随之而来了.
现在主流的前端框架都是托管在nodejs上,是通过axios来访问后端api,可以通过配置axios的代理配置(proxytable)来实现跨域访问.
那么我们的js运行在mvc上,托管在.net core上..那咋办呢?..没有现成的转发*..我们只有自己造了..
所以这就是本篇的背景 - -.~
正文
幸运的是asp.net core 给我们提供了强大的中间件模式.
我们完全可以通过定义一个转发中间件的形式来实现代理接口转发,流程如图:
废话不多说,我们来创建我们的中间件:
一.创建检测约定url的接口与实现
首先定义一个接口iurlrewriter 用来检测我们的url是否有对应前缀,如果有,则产生新的url地址:
这里我们定义接口是为了方便以后更好的更换注入类来实现快速更换检测前缀的规则.
public interface iurlrewriter { task<uri> rewriteuri(httpcontext context); }
实现这个接口,如下(解释都在注释里了):
public class prefixrewriter : iurlrewriter { private readonly pathstring _prefix; //前缀值 private readonly string _newhost; //转发的地址 public prefixrewriter(pathstring prefix, string newhost) { _prefix = prefix; _newhost = newhost; } public task<uri> rewriteuri(httpcontext context) { if (context.request.path.startswithsegments(_prefix))//判断访问是否含有前缀 { var newuri = context.request.path.value.remove(0, _prefix.value.length) + context.request.querystring; var targeturi = new uri(_newhost + newuri); return task.fromresult(targeturi); } return task.fromresult((uri)null); } }
二.创建代理转发需要的proxyhttpclient
创建独立的proxyhttpclient,主要是为了区分代理转发的httpclient,方便后期添加日志或做别的处理.代码如下:
public class proxyhttpclient { public httpclient client { get; private set; } public proxyhttpclient(httpclient httpclient) { client = httpclient; } }
三.创建代理转发的中间件
代码如下,中间件嘛,主要就是invoke方法了,说明可以看注释.
public class proxymiddleware { // private proxyhttpclient _proxyhttpclient; private const string cdn_header_name = "cache-control"; private static readonly string[] notforwardedhttpheaders = new[] { "connection", "host" }; private readonly requestdelegate _next; private readonly ilogger<proxymiddleware> _logger; public proxymiddleware( requestdelegate next, ilogger<proxymiddleware> logger ) { _next = next; _logger = logger; //_proxyhttpclient = proxyhttpclient; } /// <summary> /// 通过中间件,拦截访问,检测前缀,并转发 /// </summary> /// <param name="context"></param> /// <param name="urlrewriter"></param> /// <returns></returns> public async task invoke(httpcontext context, iurlrewriter urlrewriter, proxyhttpclient proxyhttpclient) { var targeturi = await urlrewriter.rewriteuri(context); if (targeturi != null) { var requestmessage = generateproxifiedrequest(context, targeturi); await sendasync(context, requestmessage, proxyhttpclient); return; } await _next(context); } private async task sendasync(httpcontext context, httprequestmessage requestmessage, proxyhttpclient proxyhttpclient) { using (var responsemessage = await proxyhttpclient.client.sendasync(requestmessage, httpcompletionoption.responseheadersread, context.requestaborted)) { context.response.statuscode = (int)responsemessage.statuscode; foreach (var header in responsemessage.headers) { context.response.headers[header.key] = header.value.toarray(); } foreach (var header in responsemessage.content.headers) { context.response.headers[header.key] = header.value.toarray(); } context.response.headers.remove("transfer-encoding"); if (!context.response.headers.containskey(cdn_header_name)) { context.response.headers.add(cdn_header_name, "no-cache, no-store"); } await responsemessage.content.copytoasync(context.response.body); } } private static httprequestmessage generateproxifiedrequest(httpcontext context, uri targeturi) { var requestmessage = new httprequestmessage(); copyrequestcontentandheaders(context, requestmessage); requestmessage.requesturi = targeturi; requestmessage.headers.host = targeturi.host; requestmessage.method = getmethod(context.request.method); return requestmessage; } private static void copyrequestcontentandheaders(httpcontext context, httprequestmessage requestmessage) { var requestmethod = context.request.method; if (!httpmethods.isget(requestmethod) && !httpmethods.ishead(requestmethod) && !httpmethods.isdelete(requestmethod) && !httpmethods.istrace(requestmethod)) { var streamcontent = new streamcontent(context.request.body); requestmessage.content = streamcontent; } foreach (var header in context.request.headers) { if (!notforwardedhttpheaders.contains(header.key)) { if (header.key != "user-agent") { if (!requestmessage.headers.tryaddwithoutvalidation(header.key, header.value.toarray()) && requestmessage.content != null) { requestmessage.content?.headers.tryaddwithoutvalidation(header.key, header.value.toarray()); } } else { string useragent = header.value.count > 0 ? (header.value[0] + " " + context.traceidentifier) : string.empty; if (!requestmessage.headers.tryaddwithoutvalidation(header.key, useragent) && requestmessage.content != null) { requestmessage.content?.headers.tryaddwithoutvalidation(header.key, useragent); } } } } } private static httpmethod getmethod(string method) { if (httpmethods.isdelete(method)) return httpmethod.delete; if (httpmethods.isget(method)) return httpmethod.get; if (httpmethods.ishead(method)) return httpmethod.head; if (httpmethods.isoptions(method)) return httpmethod.options; if (httpmethods.ispost(method)) return httpmethod.post; if (httpmethods.isput(method)) return httpmethod.put; if (httpmethods.istrace(method)) return httpmethod.trace; return new httpmethod(method); }
四.注入和启用我们的中间件和proxyhttpclient
我们在startup的configureservices中添加如下代码,注入我们的httpclient与iurlrewriter,如下:
services.addhttpclient<proxyhttpclient>() .configureprimaryhttpmessagehandler(x => new httpclienthandler() { allowautoredirect = false, maxconnectionsperserver = int.maxvalue, usecookies = false, }); //注入我们定义的httpclient services.addsingleton<iurlrewriter>(new prefixrewriter("/webapp", "http://localhost:63445"));//这里填写前缀与需要转发的地址
然后在startup的configure中,启动我们的中间件,如下:
app.usemiddleware<proxymiddleware>();
五.测试中间件效果
我们编写前端代码如下:
created: function () { this.mocktabledata1(); axios.get("/webapp/api/values/get", "123").then(res => { alert(res.data[0]) }); axios.post("/webapp/api/values/post",{value: 'david'}).then(res => { alert(res.data.message) }); }
在另外的webapi项目,编写接口如下:
[httpget] public actionresult<ienumerable<string>> get() { return new string[] { "value1", accstring.tostring() }; } [httppost] public ajaxresult post(dynamic value) { string aaa = jsonconvert.serializeobject(value); return success("ok"); }
效果如下,可以看到我们的视图正确的获取到了返回值:
写在最后
这里我们通过中间件的形式实现了接口的代理转发,在具体的使用过程中肯定还会有一些小问题,而且这里我们只实现了http的转发.ws的则没有.
如果要使用的话,其实国外有一个开源的项目:https://github.com/proxykit, 已经有900多个star了.应该还不错.
到此这篇关于asp.net core 奇技淫巧之接口代理转发的实现的文章就介绍到这了,更多相关asp.net core 接口代理转发内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 李莲英的三大绝活,看看他是怎么伺候慈禧的
下一篇: MySQL索引的基本语法
推荐阅读
-
ASP.NET Core 奇技淫巧之接口代理转发
-
ASP.NET Core 奇技淫巧之接口代理转发的实现
-
ASP.NET Core 使用 JWT 自定义角色/策略授权需要实现的接口
-
ASP.NET Core 奇淫技巧之伪属性注入的实现
-
ASP.NET Core奇淫技巧之动态WebApi的实现
-
ASP.NET Core使用JWT自定义角色并实现策略授权需要的接口
-
ASP.NET Core 使用 JWT 自定义角色/策略授权需要实现的接口
-
ASP.NET Core 奇技淫巧之接口代理转发的实现
-
ASP.NET Core使用JWT自定义角色并实现策略授权需要的接口
-
ASP.NET Core 奇淫技巧之伪属性注入的实现