我想要获取客户端的 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
使用此 token 访问 blob:
它在本地不起作用。
关于c# - 使用 .NET Core 3.1 和 HttpContext 的客户端 IP 地址错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66639007/