当使用httpcontext . features . getihttpconnectionfeature>(). re

本文关键字:re getihttpconnectionfeature features httpcontext | 更新日期: 2023-09-27 18:03:37

我使用asp.net core与mvc。我正在尝试使用下面的代码获得IP地址。

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

总是返回::1,这在我的本地机器上意味着127.0.0.1,这很好。但是现在我把它托管在azure云上,只是为了使用我的测试azure帐户进行测试,它仍然给我127.0.0.1。

我做错了什么?

project.json

    {
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "author": [ "Musaab Mushtaq", "Programmer" ],
      "type": "platform"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.0.0-rc2-final",
    "DeveloperForce.Force": "1.3.0",
    "Microsoft.Framework.Configuration": "1.0.0-beta8",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc2-final",
    "IntegraPay.Domain": "1.0.0-*"
  },
  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    }
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "dnxcore50",
        "portable-net45+win8",
        "net45"
      ],
      "dependencies": {
      }
    }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
  "runtimeOptions": {
    "gcServer": true
  },
  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config",
      "config.json",
      "Views"
    ]
  },
  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Startup.cs

  public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<ForwardedHeadersOptions>(option => { option.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForward‌​edFor; });
            services.AddMvc();
            services.AddSingleton(provider => Configuration);
            services.AddTransient<IRegistrationRepository, ServiceUtilities>();
            services.AddTransient<IClientServiceConnector, ClientServiceValidation>();
        }
        private IClientServiceConnector ForceClientService { get;set; }
        private IConfiguration Configuration { get; set; }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment enviroment)
        {
            app.UseStaticFiles();
            if (enviroment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Registration/Error");
            }
            app.UseRuntimeInfoPage("/Info");
            app.UseFileServer();
            ConfigureRestAuthenticationSetting(enviroment);
            app.UseMvc(ConfigureRoutes);
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
        private void ConfigureRestAuthenticationSetting(IHostingEnvironment enviroment)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(enviroment.ContentRootPath)
                .AddJsonFile("config.json");
            Configuration = config.Build();
        }
        private void ConfigureRoutes(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute("Default", "{controller=Registration}/{action=Index}/{formId?}");
        }

    }

当使用httpcontext . features . getihttpconnectionfeature>(). re

这是因为反向代理。使用ASP.net core IIS将请求发送到Kestrel服务器进行处理,然后作为MVC 6 (ASP.net core)接收请求,这个问题将会出现,因为一些标头信息将不会被转发。

下面的事情将解决你的问题。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      loggerFactory.AddDebug();
      app.UseForwardedHeaders(new ForwardedHeadersOptions() { ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.All }); // This must be first line. ( Before other middleware get configured)
      // your other code
    }

更新1 1. 不要使用服务。配置和app.UseForwardedHeaders一起。(我试过同时使用这两个选项,结果是127.0.0.1)。2. 我只使用app.UseForwardedHeaders,它工作得很好。

我的最小配置文件。(Startup.cs)

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        //services.Configure<ForwardedHeadersOptions>(option => { option.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.All; });  // This option should not be used. it gives me 127.0.0.1 if I have used this option.
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(LogLevel.Debug);
        app.UseForwardedHeaders(new ForwardedHeadersOptions() { ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.All });
        app.UseStaticFiles();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMvc();
    }
}

更新2

之后我尝试了Service。配置和它工作。在这种情况下,我只能使用Service。配置并避免使用app.UseForwardedHeaders。

在这种情况下,我的Startup.cs文件如下。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.Configure<ForwardedHeadersOptions>(option => { option.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForward‌​edFor; });  
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(LogLevel.Debug);
        //app.UseForwardedHeaders(new ForwardedHeadersOptions() { ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.All });
        app.UseStaticFiles();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMvc();
    }
}

这在云上部署时适用于我:

var forwardOpts = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All };
forwardOpts.KnownNetworks.Clear();
forwardOpts.KnownProxies.Clear();
app.UseForwardedHeaders(forwardOpts);