简体   繁体   English

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

[英]How to access server variables in ASP.Net Core 2.x

I m using ASP.Net core 2.0 web app and it is deployed on Azure. 我使用ASP.Net核心2.0 Web应用程序,它部署在Azure上。 What I need to do is to get client IP Address. 我需要做的是获取客户端IP地址。 For this, I m searching all over the internet and found that the server variables help me on this. 为此,我在互联网上搜索,发现服务器变量可以帮助我。

So I found this code from here to get Client IP using: 所以我从这里找到这个代码来获取客户端IP:

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

But when I'm trying above code it shows me an error "HttpRequest does not contain a definition for Server Variables" 但是,当我尝试上面的代码时,它向我显示一个错误“HttpRequest不包含服务器变量的定义”

Also I was try this code: 我也试过这段代码:

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

Code Definition 代码定义

RemoteIpAddress The IP Address of the client making the request. RemoteIpAddress发出请求的客户端的IP地址。 Note this may be for a proxy rather than the end user. 请注意,这可能是代理而不是最终用户。

Above code is getting the IP address but it is not a clientip and each time when I access above code via controller it refreshes the IP. 上面的代码是获取IP地址,但它不是一个clientip,每次当我通过控制器访问上面的代码时,它刷新IP。 Maybe this is an Azure web service proxy which makes get request each time. 也许这是一个Azure Web服务代理,每次都会生成get请求。

What is the right way to access server variables in ASP.Net Core 2.x? 在ASP.Net Core 2.x中访问服务器变量的正确方法是什么?

I found Mark G reference link very useful. 我发现Mark G参考链接非常有用。

I've configure the middleware with ForwardedHeadersOptions to forward the X-Forwarded-For and X-Forwarded-Proto headers in Startup.ConfigureServices. 我使用ForwardedHeadersOptions配置中间件,以在Startup.ConfigureServices中转发X-Forwarded-For和X-Forwarded-Proto头。

Here is my startup.cs code file: 这是我的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();
        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)
    {
        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?}");
        });
    }

Now after that I put below code in my 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() };
 }

So, If I'm running on my localhost environment it shows my IPv4 system IP Address and If I'm running my server on azure it shows my Host Name / IP Address. 所以,如果我在我的localhost环境中运行,它会显示我的IPv4系统IP地址,如果我在azure上运行我的服务器,它会显示我的主机名/ IP地址。

Conclusion: 结论:

I've found my answer in Mark G comment Forwarded Headers Middleware 我在Mark G评论Forwarded Headers Middleware中找到了我的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM