代码之家  ›  专栏  ›  技术社区  ›  Ahmer Ali Ahsan

如何在中访问服务器变量ASP.Net核心2.x

  •  3
  • Ahmer Ali Ahsan  · 技术社区  · 6 年前

    我正在使用ASP.Net核心2.0 web应用程序,它部署在Azure上。我需要做的是得到客户端IP地址。为此,我在互联网上搜索,发现服务器变量对我有帮助。

    所以我从 here 要使用以下方法获取客户端IP:

    string IpAddress = this.Request.ServerVariables["REMOTE_ADDR"];

    但是当我尝试上面的代码时,它显示一个错误“HttpRequest不包含服务器变量的定义”

    var ip0 = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress;
    

    代码定义

    发出请求的客户端的IP地址。注意这可能是针对代理而不是最终用户。

    上面的代码是获取IP地址,但它不是clientip,每次我通过controller访问上面的代码时,它都会刷新IP。也许这是一个Azure web服务代理,每次都会发出get请求。

    2 回复  |  直到 4 年前
        2
  •  4
  •   Peter Csala Matheus Robert Lichtnow    4 年前

    我发现马克G的参考链接非常有用。

    我已经将中间件配置为 ForwardedHeadersOptions X-Forwarded-For X-Forwarded-Proto Startup.ConfigureServices .

    这是我的 代码文件:

    配置服务

    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?}");
        });
    }
    

    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地址。

    结论:

    Forwarded Headers Middleware