我使用的是 ASP.Net core 2.0 网络应用程序,它部署在 Azure 上。我需要做的是获取客户端 IP 地址。为此,我在整个互联网上进行了搜索,发现服务器变量可以帮助我解决这个问题。
所以我从here中找到了这段代码使用以下方法获取客户端 IP:
string IpAddress = this.Request.ServerVariables["REMOTE_ADDR"];
但是当我尝试上面的代码时,它向我显示错误“HttpRequest 不包含服务器变量的定义”
我也试过这段代码:
var ip0 = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress;
代码定义
RemoteIpAddress The IP Address of the client making the request. Note this may be for a proxy rather than the end user.
上面的代码正在获取 IP 地址,但它不是 clientip,每次当我通过 Controller 访问上面的代码时,它都会刷新 IP。也许这是一个 Azure Web 服务代理,它每次都发出 get 请求。
在 ASP.Net Core 2.x 中访问服务器变量的正确方法是什么?
最佳答案
我发现 Mark G 的引用链接非常有用。
我用 ForwardedHeadersOptions
配置了中间件转发X-Forwarded-For
和 X-Forwarded-Proto
Startup.ConfigureServices
中的标题.
这是我的Startup.cs代码文件:
配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>();
services.AddCors(options =>
{
options.AddPolicy("AllowClient",
builder => builder.WithOrigins("http://**.asyncsol.com", "http://*.asyncsol.com", "http://localhost:10761", "https://localhost:44335")
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc();
/* The relevant part for Forwarded Headers */
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
// base-address of your identityserver
//options.Authority = "http://server.asyncsol.com/";
options.Authority = "http://localhost:52718/";
// name of the API resource
options.Audience = "api1";
options.RequireHttpsMetadata = false;
});
}
配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
/* The relevant part for Forwarded Headers */
app.UseForwardedHeaders();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseAuthentication();
app.UseCors("AllowAll");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在 Controller 中的使用
public IEnumerable<string> Get()
{
string ip = Response.HttpContext.Connection.RemoteIpAddress.ToString();
//https://en.wikipedia.org/wiki/Localhost
//127.0.0.1 localhost
//::1 localhost
if (ip == "::1")
{
ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[2].ToString();
}
return new string[] { ip.ToString() };
}
因此,如果我在本地主机环境中运行,它会显示我的 IPv4 系统 IP 地址。
如果我在 Azure 上运行我的服务器,它会显示我的主机名/IP 地址。
结论:
我在 Mark G 评论 Forwarded Headers Middleware 中找到了我的答案
关于c# - 如何在 ASP.Net Core 2.x 中访问服务器变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51394593/