您好,登錄后才能下訂單哦!
本文章向大家介紹如何在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。