首页 > 解决方案 > 在 IIS 中运行的 Blazor 服务器端应用程序中获取远程 IP 地址不起作用?

问题描述

我需要获取客户端的IP地址,所以我做了以下事情:

  1. 创建了一个控制器并添加了这个动作:

     [HttpGet("[action]")]
     public ActionResult IpAddress()
     {
         var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
         if (remoteIpAddress != null)
             return Ok(remoteIpAddress.ToString());
    
         return new EmptyResult();
     }
    
  2. 将以下脚本添加到我的site.js

     window.getIpAddress = () => {
         return fetch('/api/utils/ipaddress')
             .then((response) => response.text())
             .then((data) => {
                 return data
             })
     }
    
  3. 也设置Startup.cs到用户控制器,还添加以下内容:

         app.UseForwardedHeaders(new ForwardedHeadersOptions
         {
             ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
         });
    
  4. 最后,将以下内容添加到我的剃须刀组件中:

     var ipAddress = await jsRuntime.InvokeAsync<string>("getIpAddress").ConfigureAwait(true);
    

然后我发布到 IIS 并访问该应用程序。

但是,IP地址不是客户端的IP地址(实际上是标准网关的值),而是运行IIS的机器的IP地址!

我究竟做错了什么?

标签: javascriptc#iisblazorblazor-server-side

解决方案


推荐阅读