-1
如何在asp.net核心中執行代理服務,請求將被路由到其他服務的擴展。asp.net核心通用代理
我的擴展:
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);
}
添加到內容後,把參數,與應用程序/ x-WWW窗體-urlencoded或應用程序/表單數據,併發送到其他服務,但我沒有得到這個參數在其他服務。 幫幫我,需要發佈這個功能。 Thx,對不起我的英文不好