本文章向大家介绍如何在ASP.NET中实现一个接口代理转发功能的基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
ASP.NET 是开源,跨平台,高性能,轻量级的 Web 应用构建框架,常用于通过 HTML、CSS、JavaScript 以及服务器脚本来构建网页和网站。
首先定义一个接口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"); }
效果如下,可以看到我们的视图正确的获取到了返回值:
以上就是小编为大家带来的如何在ASP.NET中实现一个接口代理转发功能的全部内容了,希望大家多多支持亿速云!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。