从 nginx 代理后面的 dotnet core 获取 gull 请求 URL

问题描述 投票:0回答:1

我需要从调用 api 的 dotnet-core webapi 获取 URL。 API 本身托管在特定位置的 nginx 代理后面:

nginx 配置:

server {
    server_name my.domain.com;
    root /var/www/html/someotherapp;
    index index.php;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log info;

    location /myapi/ {
            proxy_pass http://localhost:8181/;
            proxy_buffering off;
            proxy_read_timeout 7200;

            proxy_set_header Upgrade           $http_upgrade;
            proxy_set_header Connection        "upgrade";
            proxy_set_header Host              $host;
            proxy_set_header X-Real-IP         $remote_addr;
            proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host  $host;
            proxy_set_header X-Forwarded-Port  $server_port;

    }
    location / {
            index index.html;
    }

listen 443 ssl; # managed by Certbot
}

dotnet API:

在startup.configureservices中:

services.Configure<ForwardedHeadersOptions>(options =>
{
  options.ForwardedHeaders =
    ForwardedHeaders.All;
});

和startup.configure

app.UseForwardedHeaders();

我现在可以通过

调用这个应用程序

https://my.domain.com/myapi/api/testapi?myquery=test

当尝试获取控制器中调用我的 URL 时,类似于

$"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}{HttpContext.Request.Path}{HttpContext.Request.QueryString}";

我不会知道代理转发的位置,所以结果始终是

https://my.domain.com/api/testapi?myquery=test

缺少“myapi”位置。

知道如何获取位置吗?

nginx asp.net-web-api .net-core nginx-reverse-proxy
1个回答
0
投票

就我而言,这可能与您的情况不完全相关,我正在制作一个 CMS,我希望布局根据请求来自的域进行更改。这离理想还很远,但我只是向主机文件添加了值来更改 localhost proxypass url

为此,您需要在

/etc/hosts
添加以下行

127.0.0.1    tinderbutfordogs

然后在

https://tinderbutfordogs.club
下的
/etc/nginx/sites-available/tinderbutfordogs.club.conf
的 nginx 配置中,我从此更新了
proxy_pass

proxy_pass https://localhost:5001;

proxy_pass https://tinderbutfordogs:5001;

然后在我的 dotnet core web 应用程序中,如果我将值

Request.Host.Value
传递给我的视图数据,我可以在我的 razor 代码中使用以下内容

public IActionResult Index() 
{
  ViewData["host"] = Request.Host.Value;
  
  return View();
}

剃刀视图

@{
    Layout = @ViewData["host"]; // Value is tinderbutfordogs:5001
}

注意:如果您希望找到布局,则需要将其命名为

tinderbutfordogs
,不带
.cshtml
扩展名,否则 dotnet 在使用
:
查找您所请求的视图布局时会出现问题。

无论如何,这就是我用来克服问题的方法,希望它能有所帮助,即使这不完全是您想要实现的目标!

© www.soinside.com 2019 - 2024. All rights reserved.