如何实现asp.net core通用代理

本文关键字:core net 代理 asp 何实现 实现 | 更新日期: 2023-09-27 18:07:16

我在asp.net core做代理服务,扩展中请求将被路由到另一个服务

My extension:

 public static IApplicationBuilder UseProxy(this IApplicationBuilder builder, List<ProxySetting> options)
    {
        builder.Use(async (context, next) =>
        {
            var resultPathHandler = options.ProxySettingHandler(context.Request.Path, context.Request.Method);
            if (!resultPathHandler.Equal)
                //continues through the rest of the pipeline
                await next();
            else
            {
                using (var httpClient = new HttpClient())
                {
                    var pathSetting = resultPathHandler.Setting;
                    var requestMessage = new HttpRequestMessage();
                    //добавляем хедеры
                    foreach (var header in context.Request.Headers)
                    {
                        if (!httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value.ToArray()))
                        {
                            httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key,
                                header.Value.ToArray());
                        }
                    }

                    if (context.Request.HasFormContentType && context.Request.Form.Count > 0)
                    {
                        var temp = new Dictionary<string, object>();
                        foreach (var form in context.Request.Form)
                        {
                            requestMessage.Properties.Add(form.Key, form.Value);
                            temp.Add(form.Key, form.Value);
                        }
                        var jsonString = JsonConvert.SerializeObject(temp).Replace(":[", ":").Replace("],",",");
                        var mediatype = string.Empty;
                        if (context.Request.ContentType.Contains(';'))
                            mediatype = context.Request.ContentType.Split(';')[0];
                        else
                            mediatype = context.Request.ContentType;
                        requestMessage.Content = new StringContent(jsonString, Encoding.UTF8, mediatype);
                    }
                    requestMessage.Headers.Host = pathSetting.Host;
                    var host = pathSetting.GetUri(context.Request.Path);
                    var uriString = $"{host}{context.Request.QueryString}";
                    requestMessage.RequestUri = new Uri(uriString);
                    requestMessage.Method = new HttpMethod(pathSetting.Method);
                    var response = await httpClient.SendAsync(requestMessage);
                    var result = await response.Content.ReadAsStringAsync();
                    var resultObj = JsonConvert.DeserializeObject<object>(result);
                    context.Response.StatusCode = (int)response.StatusCode;
                    await context.Response.WriteAsync(resultObj.ToString());
                }
            }
        });
        return builder;
    }
                if (context.Request.HasFormContentType && context.Request.Form.Count > 0)
                {
                    var temp = new Dictionary<string, object>();
                    foreach (var form in context.Request.Form)
                    {
                        requestMessage.Properties.Add(form.Key, form.Value);
                        temp.Add(form.Key, form.Value);
                    }
                    var jsonString = JsonConvert.SerializeObject(temp).Replace(":[", ":").Replace("],",",");
                    var mediatype = string.Empty;
                    if (context.Request.ContentType.Contains(';'))
                        mediatype = context.Request.ContentType.Split(';')[0];
                    else
                        mediatype = context.Request.ContentType;
                    requestMessage.Content = new StringContent(jsonString, Encoding.UTF8, mediatype);
                }

给内容添加post和put参数,使用application/x-www-form-urlencoded或application/form-data,并发送给其他服务,但在其他服务中无法获得此参数。帮帮我,需要发布这个功能。

如何实现asp.net core通用代理

你不需要重新发明轮子。ASP。. NET Core已经拥有并提供了自己的ProxyMiddleware