Asp.net core Asp.net core 2.0 mvc应用程序使用负载平衡器选项获取客户端ip地址
我无法使用.net core 2.0应用程序获取客户端IP地址 我在startup.cs文件中使用了以下代码 我在homecontriller.cs文件中使用了以下代码 我得到的remoteIpAddress在本地为1.0.0.0。当我部署到服务器时,我得到了服务器IP地址,但我想显示客户端IP地址。 你能帮个忙吗。谢谢Asp.net core Asp.net core 2.0 mvc应用程序使用负载平衡器选项获取客户端ip地址,asp.net-core,.net-core,asp.net-core-mvc,asp.net-core-2.0,asp.net-core-2.1,Asp.net Core,.net Core,Asp.net Core Mvc,Asp.net Core 2.0,Asp.net Core 2.1,我无法使用.net core 2.0应用程序获取客户端IP地址 我在startup.cs文件中使用了以下代码 我在homecontriller.cs文件中使用了以下代码 我得到的remoteIpAddress在本地为1.0.0.0。当我部署到服务器时,我得到了服务器IP地址,但我想显示客户端IP地址。 你能帮个忙吗。谢谢 services.Configure<ForwardedHeadersOptions> (options => { options.ForwardedHea
services.Configure<ForwardedHeadersOptions> (options => {
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor> ();
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor> ();
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseForwardedHeaders(new ForwardedHeadersOptions {
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
}
public IActionResult Index() {
string remoteIpAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
if (Request.Headers.ContainsKey("X-Forwarded-For")) {
remoteIpAddress = Request.Headers["X-Forwarded-For"];
}
ViewBag.ip1 = remoteIpAddress.ToString();
return View();
}
services.Configure(选项=>{
options.ForwardedHeaders=ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddSingleton();
AddHttpContextAccessor();
services.TryAddSingleton();
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境){
app.UseForwardedHeaders(新ForwardedHeaders选项{
ForwardedHeaders=ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
}
公共IActionResult索引(){
字符串remoteIpAddress=HttpContext.Connection.remoteIpAddress.MapToIPv4().ToString();
if(Request.Headers.ContainsKey(“X-Forwarded-For”)){
remoteIpAddress=Request.Headers[“X-Forwarded-For”];
}
ViewBag.ip1=remoteIpAddress.ToString();
返回视图();
}
在project.json中添加依赖项:
"Microsoft.AspNetCore.HttpOverrides": "1.0.0"
在Startup.cs中,在Configure()方法中添加:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
和在控制器中
using Microsoft.AspNetCore.HttpOverrides;
这样你就可以得到IP地址了
Request.HttpContext.Connection.RemoteIpAddress
你提到了文件名,但不是代码本身,请添加代码。我添加了代码@YashKarankei发布了代码@YashKarankei谢谢我已经尝试了以下一个,但没有用。它提供服务器IP地址,而不是提供客户端计算机IP地址Request.HttpContext.Connection。RemoteIpAddress@Harry,然后参考此链接,我希望这将解决您的问题,谢谢您的回复。我也尝试过这个方法,但效果相同。如果有其他解决方案,请告诉我。谢谢你的帮助