我正在使用一个过滤器来检查用户到达网站时的浏览器/版本。如果他们使用不受支持的浏览器,我会将他们打算访问的 URL 保存到名为“RequestedURL”的 ViewData 中,并重定向到一个视图,告诉他们他们的浏览器是旧的。此视图使用户能够通过单击链接继续操作。此链接的 URL 由过滤器中设置的“RequestedUrl”的 ViewData 属性填充。
筛选:
/// <summary>
/// If the user has a browser we don't support, this will present them with a page that tells them they have an old browser. This check is done only when they first visit the site. A cookie also prevents unnecessary future checks, so this won't slow the app down.
/// </summary>
public class WarnAboutUnsupportedBrowserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
//this will be true when it's their first visit to the site (will happen again if they clear cookies)
if (request.UrlReferrer == null && request.Cookies["browserChecked"] == null)
{
//give old IE users a warning the first time
if ((request.Browser.Browser.Trim().ToUpperInvariant().Equals("IE") && request.Browser.MajorVersion <= 7) ||
(request.Browser.Browser.Trim().ToUpperInvariant().Equals("Chrome") && request.Browser.MajorVersion <= 22) ||
(request.Browser.Browser.Trim().ToUpperInvariant().Equals("Mozilla") && request.Browser.MajorVersion <= 16) ||
(request.Browser.Browser.Trim().ToUpperInvariant().Equals("Safari") && request.Browser.MajorVersion <= 4))
{
filterContext.Controller.ViewData["RequestedUrl"] = request.Url.ToString();
filterContext.Result = new ViewResult { ViewName = "UnsupportedBrowserWarning" };
}
filterContext.HttpContext.Response.AppendCookie(new HttpCookie("browserChecked", "true"));
}
}
}
查看对 ViewData 的引用:
<a href="@ViewData["RequestedUrl"] ">Thanks for letting me know.</a>
大多数网址都可以正常工作。当用户输入一个包含参数的 URL 时,问题就出现了。例如:
[WarnAboutUnsupportedBrowser]
public ActionResult Index(string providerkey)
如果用户输入的 Url 是“../Controller/Foo/providerkey”,则在视图中填充的 Url 是“Controller/Foo”,其中缺少访问页面所需的参数。
如何确保视图中的 URL 是用户最初输入的整个 URL?