我遇到标题错误。这是完整的错误显示
'HttpRequest'不包含'Browser'的定义,并且找不到可访问的扩展方法'Browser'接受类型为'HttpRequest'的第一个参数(您是否缺少using指令或程序集引用? )
现在,当我编写代码以检查网站是否在计算机或移动上运行时,此错误向我显示。
我尝试也为HTTPRequest
提供参考,但在nuget package
中找不到
这是我的控制器代码,
public ActionResult MobileBrowser()
{
var browser = Request.Browser;
System.Web.HttpBrowserCapabilitiesBase myBrowserCaps = browser;
if (((System.Web.HttpBrowserCapabilitiesBase)myBrowserCaps).IsMobileDevice)
{
ViewBag.Message = "mob";
}
else
{
ViewBag.Message = "web";
}
return PartialView();
}
现在,我在var browser = Request.Browser;
,System.Web.HttpBrowserCapabilitiesBase myBrowserCaps = browser;
和if (((System.Web.HttpBrowserCapabilitiesBase)myBrowserCaps).IsMobileDevice)
答案 0 :(得分:0)
在nopCommerce中,他们提供的是在移动设备中使用的网站,或者不使用以下服务
/// <summary>
/// Get a value indicating whether the request is made by mobile device
/// </summary>
/// <returns></returns>
public virtual bool IsMobileDevice()
{
if (_httpContextAccessor?.HttpContext == null)
return false;
//we put required logic in try-catch block
//more info: https://www.nopcommerce.com/boards/t/17711/unhandled-exception-request-is-not-available-in-this-context.aspx
try
{
//we don't parse browscap library here
//in 99% of cases it's enough to use the approach suggested by http://detectmobilebrowsers.com/
var userAgent = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent].ToString();
var mobile = _firstMobileDeviceRegex.IsMatch(userAgent) || _secondMobileDeviceRegex.IsMatch(userAgent.Substring(0, 4));
return mobile;
}
catch
{
// ignored
}
return false;
}
或者您可以使用
代替请求浏览器var userAgent = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent].ToString();
所以这肯定会有所帮助
希望这对您有帮助
谢谢
答案 1 :(得分:0)
您可以尝试-
public class UploadFileController : Controller { [HttpGet] public IActionResult Photo() { var brows = Request.Headers["User-Agent"].ToString(); return View(); } [HttpPost] public IActionResult Photo(UserViewModel userViewModel) { if (ModelState.IsValid) { } return View(userViewModel); } }
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
中指定的类型的单例服务。现在您可以注入控制器了-public class UploadFileController : Controller { private readonly IHttpContextAccessor httpContextAccessor; public UploadFileController(IHttpContextAccessor httpContext) { this.httpContextAccessor = httpContext; } [HttpGet] public IActionResult Photo() { var browser = httpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString(); return View(); } [HttpPost] public IActionResult Photo(UserViewModel userViewModel) { if (ModelState.IsValid) { } return View(userViewModel); } }
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
中添加并注入IHttpContextAccessor。@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor @{ ViewData["Title"] = "Upload Picture"; var browser = HttpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString(); }