c# - 使用 .NET Core 3.1 和 HttpContext 的客户端 IP 地址错误

标签 c# azure asp.net-core azure-blob-storage

我想要获取客户端的 IP 地址(例如 Chrome 浏览器),然后使用它为我的 Blob 存储资源生成 SAS token 。

为此,我使用以下代码行:

// In Startup.cs class:

services.AddHttpContextAccessor();

// In controller method:
// _httpContextAccessor is IHttpContextAccessor interface

var clientIpAddress = _httpContextAccessor.HttpContext.Request.HttpContext.Connection.RemoteIpAddress;

var blobClient = blobContainerClient.GetBlobClient();
var blobSasBuilder = new BlobSasBuilder
{
    StartsOn = now, 
    ExpiresOn = now.AddMinutes(10),
    BlobContainerName = blobClient.BlobContainerName,
    IPRange = new SasIPRange(clientIpAddress) // im using clientIpAddress here
};

当我在 https://www.myip.com/ 站点检查我的 IP 时,我得到了与 Azure 门户 GUI 一起使用的 IP,用于生成 sas token (生成后我可以访问 Blob )

当我将应用程序部署到 Azure 时,IP 与 https://www.myip.com/ 站点中的 IP 完全不同,并且不允许我为 chrome 浏览器生成 sas token 。

我的问题是,为什么当我将应用程序部署到 Azure 时 HttpContext 返回错误的客户端 Ip 地址?

最佳答案

根据我的理解,您希望生成一个 SAS token ,用于请求具有客户端公共(public) IP 地址限制的客户端。我写了一个简单的 Controller ,可以满足您的要求:

using System;
using Azure.Storage.Blobs;
using Azure.Storage.Sas;
using Microsoft.AspNetCore.Mvc;

namespace getSasTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SasTokenController : ControllerBase
    {
        [HttpGet]
        public string get()
        {
            var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
            var connstr = "<your connection string here>";
            var container = "files";
            var blob = "test.txt";

            var blobClient = new BlobContainerClient(connstr,container).GetBlobClient(blob);
            var blobSasBuilder = new BlobSasBuilder
            {
                BlobContainerName = blobClient.BlobContainerName,
                BlobName = blobClient.Name,
                IPRange = new SasIPRange(remoteIpAddress),
            };


            blobSasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(10);
            blobSasBuilder.SetPermissions(BlobSasPermissions.Read);

            var sas = blobClient.GenerateSasUri(blobSasBuilder);


            return sas.ToString();
        }

       
    }
}

您可以尝试在此处获取 SAS token 进行测试: https://stanwinapp.azurewebsites.net/sastoken

结果: enter image description here enter image description here

使用此 token 访问 blob:

enter image description here

它在本地不起作用。

关于c# - 使用 .NET Core 3.1 和 HttpContext 的客户端 IP 地址错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66639007/

相关文章:

asp.net-core - EF Core 2 如何在 IdentityUser 上包含角色导航属性?

c# - 在 asp.net core 中使用 NVarChar

c# - 回发后由 jquery 设置时如何获取隐藏在 C# 中的值

c# - 改变当前方法的执行线程

windows - 站点到站点 VPN 与点到站点 VPN

azure - Cloud Foundry 部署出现 Bosh 错误 - "Unable to get deployment lock, maybe a deployment is in progress. Try again later."

azure - 如何在 Azure 中的 ubuntu 中启用互联网连接

C# WPF 线程如何正确停止

c# - 如何递归迭代日期的数字和总和?

c# - .NET Core EntityFramework Identity - 更改 IdentityOptions(不在 Startup.cs 中)