【问题标题】:getting an error when trying to get a users IP address尝试获取用户 IP 地址时出错
【发布时间】:2021-03-16 15:26:59
【问题描述】:

错误是这样的:

严重性代码描述项目文件行抑制状态 错误 CS1061 'HttpRequest' 不包含 'ServerVariables' 的定义,并且找不到接受第一个类型为 'HttpRequest' 的参数的可访问扩展方法 'ServerVariables'(您是否缺少 using 指令或程序集引用?) Elearn C: \Users\Isaac Bredbenner\source\repos\Elearm_Finalchanges\Elearn\Elearn\Controllers\AccountController.cs 161 活动

[HttpPost]
public IActionResult CookieConsents()
{
    CookieConsents cookieConsents = new CookieConsents
    {
       Consent = true,
       IpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"],
       ConsentReceivedOn = DateTime.Now
    };
    _elearnContext.CookieConsents.Add(cookieConsents);
    _elearnContext.SaveChanges();
    return View();
}

我一直在尝试研究这个错误,我发现一个表单告诉我安装一个包,但即使在 Visual Studio 上安装它之后,我也收到了这个错误。 我的文件导入如下:

using DAL.Context;
using DAL.Models;
using DAL.Resources;
using Elearn.Helpers;
using Elearn.Infrastructure;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using X.PagedList;

我是否需要使用 httpRequest 或类似的东西?如果有人对我的问题的根源有任何想法,请告诉我。

【问题讨论】:

  • HttpRequest 是 System.Web 的一部分,所以你应该很好。这是一本很好的读物,可能会更好地理解您 - totaluptime.com/kb/…

标签: c# asp.net-mvc


【解决方案1】:

如果您使用的是 .net core,则它不可用:try this link

请求的页面不适用于 .NET Core 3.1。您已被重定向到此页面适用的最新产品版本。

你可以做的是从ConnectionInfo获取相关信息

远程IP地址

HttpContext.Connection.RemoteIpAddress;

访问上下文的详细信息可以在这里找到:How to get Client IP address in ASP.NET Core 2.1

【讨论】:

  • 请记住,如果您的服务器位于负载平衡器后面,RemoteIpAddress 可能无效(或者可能是 localhost、::1)。在这种情况下,您应该将 LB 配置为传递原始 HTTP_X_FORWARDED_FOR(或它的任何属性)。
猜你喜欢
  • 1970-01-01
  • 2019-09-10
  • 2014-09-27
  • 2011-02-06
  • 2012-06-12
  • 2011-01-12
  • 2015-03-23
  • 2013-08-01
  • 2014-08-23
相关资源
最近更新 更多