如何在ASP.Net Core 2.x中访问服务器变量 [英] How to access server variables in ASP.Net Core 2.x

查看:82
本文介绍了如何在ASP.Net Core 2.x中访问服务器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.Net core 2.0 Web应用程序,并将其部署在Azure上.我需要做的是获取客户端IP地址.为此,我在整个Internet上进行搜索,发现服务器变量对此有所帮助.

I m using ASP.Net core 2.0 web app and it is deployed on Azure. What I need to do is to get client IP Address. For this, I m searching all over the internet and found that the server variables help me on this.

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

So I found this code from here to get Client IP using:

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

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

But when I'm trying above code it shows me an error "HttpRequest does not contain a definition for Server Variables"

我也尝试过以下代码:

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

代码定义

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

RemoteIpAddress The IP Address of the client making the request. Note this may be for a proxy rather than the end user.

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

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. Maybe this is an Azure web service proxy which makes get request each time.

在ASP.Net Core 2.x中访问服务器变量的正确方法是什么?

What is the right way to access server variables in ASP.Net Core 2.x?

推荐答案

我发现Mark G的参考链接非常有用.

I've found Mark G's reference link very useful.

我已使用ForwardedHeadersOptions配置中间件以转发Startup.ConfigureServices中的X-Forwarded-ForX-Forwarded-Proto标头.

I've configure the middleware with ForwardedHeadersOptions to forward the X-Forwarded-For and X-Forwarded-Proto headers in 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?}");
    });
}

在控制器上的用法

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

So, If I'm running on my localhost environment it shows my IPv4 system IP Address.
If I'm running my server on azure it shows my Host Name / IP Address.

结论:

我已经在Mark G评论

I've found my answer in Mark G comment Forwarded Headers Middleware

这篇关于如何在ASP.Net Core 2.x中访问服务器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆