天天看點

java和asp.net core_在ASP.NET Core中擷取用戶端和伺服器端的IP位址(轉載)

随着ASP.NET的發展,有不同的方式從請求中通路用戶端IP位址。WebForms和MVC Web應用程式隻是通路目前HTTP上下文的請求。

var ip = HttpContext.Current.Request.UserHostAddress;

或者隻是直接引用目前的Request

var ip = Request.UserHostAddress;

但是,這在ASP.NET Core 2.0及更高版本中不起作用。您必須從ConfigureServices方法中的Startup.cs類中注入HttpContextAccessor執行個體。

public void ConfigureServices(IServiceCollection services)

{

services.AddSingleton();

services.AddMvc();

}

現在我們需要在我們的控制器構造函數中使用它并将其配置設定給控制器級别聲明的變量,這樣,它可以從控制器中的所有Actions通路,注意我們這裡還使用了NetworkInterface.GetAllNetworkInterfaces()方法來擷取伺服器上所有網卡的IP位址:

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Http;

using System.Net;

using System.Net.NetworkInformation;

using System.Linq;

using System.Net.Sockets;

namespace AspNetCoreIP.Controllers

{

public class HomeController : Controller

{

protected readonly IHttpContextAccessor httpContextAccessor;

public HomeController(IHttpContextAccessor httpContextAccessor)

{

this.httpContextAccessor = httpContextAccessor;

}

public IActionResult Index()

{

//擷取用戶端的IP位址

string clientIpAddress = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

this.ViewData["ClientIpAddress"] = clientIpAddress;

//擷取伺服器上所有網卡的IP位址

NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces();

string serverIpAddresses = string.Empty;

foreach (var network in networks)

{

var ipAddress = network.GetIPProperties().UnicastAddresses.Where(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address)).FirstOrDefault()?.Address.ToString();

serverIpAddresses += network.Name + ":" + ipAddress + "|";

}

this.ViewData["ServerIpAddresses"] = serverIpAddresses;

return View();

}

}

}

建立MVC視圖Index.cshtml,來顯示用戶端和伺服器端的IP位址:

@{

Layout = null;

}

Index

用戶端IP位址:@this.ViewData["ClientIpAddress"].ToString()

伺服器所有網卡的IP位址:@this.ViewData["ServerIpAddresses"].ToString()

為什麼有時候httpContextAccessor.HttpContext.Connection.RemoteIpAddress擷取到的用戶端IP位址為空,請參見下文連結:

https://www.cnblogs.com/OpenCoder/category/1132736.html