在.NET MVC中,是否有一种简单的方法来检查我是否在主页上? [英] In .NET MVC, is there an easy way to check if I'm on the home page?

查看:63
本文介绍了在.NET MVC中,是否有一种简单的方法来检查我是否在主页上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户从主页登录,我需要采取特定的措施.在我的LogOnModel中,我有一个隐藏字段:

I need to take a particular action if a user logs in from the home page. In my LogOnModel, I have a hidden field:

@Html.Hidden("returnUrl", Request.Url.AbsoluteUri)

在我的控制器中,我需要检查该值是否为主页".在下面的示例中,我正在检查用户是否在特定页面上("Account/ResetPassword").有没有办法检查它们是否在主页上而无需使用正则表达式?

In my Controller, I need to check if that value is the Home page or not. In the example below, I'm checking to see if the user is on a particular page ("Account/ResetPassword"). Is there a way to check to see if they're on the home page without resorting to regular expressions?

    [HttpPost]
    public ActionResult LogOnInt(LogOnModel model)
    {
       if (model.returnUrl.Contains("/Account/ResetPassword"))
       {
          return Json(new { redirectToUrl = @Url.Action("Index","Home")});
       }

有什么想法吗?一百万个谢谢!

Any ideas? A million thanks!

推荐答案

一种解决方法是在RouteData中查找特定的控制器.假设您用于主页的控制器称为"HomeController",则请求的RouteData将包含键"Controller"的值"Home".

One way to approach this would be to look for the specific controller in the RouteData. Assuming that the controller you are using for the home page is called "HomeController", then the RouteData for the request would contain the value "Home" for the key "Controller".

它看起来像这样:

而不是(或者除了其他原因之外):

instead of (or in addition to if you have other reasons for it):

 @Html.Hidden("returnUrl", Request.Url.AbsoluteUri)

您将拥有:

 @Html.Hidden("referrer", Request.RequestContext.RouteData.Values['Controller'])

和您的控制器如下所示:

and your controller would look like:

[HttpPost]
public ActionResult LogOnInt(LogOnModel model)
{
   if (model.referrer = "Home")
   {
      return Json(new { redirectToUrl = @Url.Action("Index","Home")});
   }
 }

这将消除使用.Contains()

更新 :

Update:

您还可以通过将引荐来源网址(Request.UrlReferrer.AbsoluteUri)映射到路由来消除对隐藏字段的需求(从而减少应用程序中每个页面的整体页面权重).这里有一篇关于这个的帖子.

You could also eliminate the need for a hidden field (and thereby reduce overall page-weight for what would seem like every page in your application) by mapping the referrer url (Request.UrlReferrer.AbsoluteUri) to a route. There is a post about that here.

如何通过URL获取RouteData?

这个想法是使用mvc引擎在LogOnInt方法中将引荐来源网址映射到MVC路由,从而使代码完全独立.

The idea would be to use the mvc engine to map a referrer url to an MVC route in the LogOnInt method, allowing the code to be entirely self contained.

这可能比将控制器名称和操作名称放置在那里以供全世界查看以及将其推回服务器的脚本更干净.

This would probably be cleaner than putting the controller name and action name out there for the world to see along with scripting to push it back to the server.

这篇关于在.NET MVC中,是否有一种简单的方法来检查我是否在主页上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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