Kestrel在向HTTPS endoit发出请求时是否需要UseHttps



我在反向代理(Nginx(后面配置了Kestrel。我正在尝试使用一个端点(HTTPS(,但我一直得到:

Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException:无效的请求行。

在互联网上搜索了一段时间后,我看到有人认为这是因为我从HTTPS端点访问了HTTP端点,但在我的情况下,我从HTTP访问了HTTPS端点,不太确定如何处理。我正在做一些修改后的请求:

var json = JsonConvert.SerializeObject(new{ FieldA = "A", FieldB = "B" });
var request = new HttpRequestMessage(new HttpMethod("POST"), "/api/some-endpoint")
{
Content = new StringContent(json, Encoding.UTF8)
};
request.Content.Headers.Add(HeaderNames.ContentType, MediaTypeNames.Application.Json);
var client = httpClientFactory.CreateClient("my-client");
var response = await client.SendAsync(request);
var myResp = await response.Content.ReadAsAsync<MyResponse>();

我以以下方式注册IHttpClientFactory

services.AddHttpClient("my-client", (sp, c) =>
{
var opts = sp.GetRequiredService<IOptions<MyOptions>>().Value;
var uriB = new UriBuilder
{
Host = opts.Host,
Port = opts.Port,
Scheme = Uri.UriSchemeHttps
};
c.BaseAddress = uriB.Uri;
});

我不希望仅仅为了这个而将Kestrel配置为UseHttps,因为我让Nginx负责从外部世界到我的应用程序中的HTTPS。有什么我可以做的吗?(假设可以解决错误(?

UPDATE:我的目标是.Net Core 2.1版本,我以以下方式使用转发的头中间件:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost
});

它也是我在Startup.Configure方法中使用的第一个中间件。我的Nginx位置配置为:

location /api {
proxy_pass         http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header   Upgrade $http_upgrade;
proxy_set_header   Connection keep-alive;
proxy_set_header   Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header   X-Forwarded-Proto $scheme;
}

问题在于我构建请求的方式。我遵循了@Tseng的建议,但我一直收到错误,我甚至明确地更改了转发头的名称,以匹配我在Nginx配置中设置的名称(以防万一(,但运气不佳。这就是我的工作方式:

var json = JsonConvert.SerializeObject(new{ FieldA = "A", FieldB = "B" });
var request = new HttpRequestMessage(new HttpMethod("POST"), "/api/some-endpoint")
{
Content = new StringContent(json, Encoding.UTF8)
};
//Changed this line. I think the previous line was the problem 'cause 
// I saw a header duplication error in the stack trace referring to
// the content type header, so overriding the header may have 
// made the error gone
request.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Application.Json);
var client = httpClientFactory.CreateClient("my-client");
var response = await client.SendAsync(request);
var myResp = await response.Content.ReadAsAsync<MyResponse>();

并将我的IHttpClientFactory配置更新为:

services.AddHttpClient("my-client", (sp, c) =>
{
var opts = sp.GetRequiredService<IOptions<MyOptions>>().Value;
var uriB = new UriBuilder
{
Host = opts.Host,
Port = opts.Port,
Scheme = Uri.UriSchemeHttps
};
c.BaseAddress = uriB.Uri;
// Added this line
c.DefaultRequestHeaders.Add(HeaderNames.Accept, MediaTypeNames.Application.Json);
});

这篇文章帮助我做出了改变。希望这对将来的人有所帮助。

最新更新