【问题标题】:Custom ActionFilter to check the existence of the parametre in Database自定义操作过滤器以检查数据库中参数的存在
【发布时间】:2011-07-28 15:11:45
【问题描述】:

您好,我正在寻找解决此问题的解决方案。我正在使用 Asp.net mvc3 构建一个 Web 应用程序。 我想制作一个自定义操作过滤器([KeyAuthorization]),以便只有授权的密钥才能访问控制器。

这是我的默认路线

routes.MapRoute(
                "Default", // Route name
               "{guid}/{controller}/{action}", // URL with parameters
               new { guid = UrlParameter.Optional, controller = "Home", action = "Index", }

假设有人访问 www.example.com/34safd-234s/home/index

如果 key:34safd-234s 正确(授权),用户将看到内容,否则网络应用程序将抛出 404。

如何做到这一点?

谢谢,

如何构建和操作过滤器来检查 guid 参数是否存在于

【问题讨论】:

  • 使用动作过滤器检查数据库中的某些值只有在您需要在更多动作上使用此逻辑时才有意义,否则最好检查动作中的值而不是选择要返回的视图。
  • 另一种方法是使用路由约束stephenwalther.com/blog/archive/2008/08/07/…
  • 是的,我在所有操作中都需要它,是某种 api

标签: asp.net-mvc-3 action-filter


【解决方案1】:

您可以通过创建ActionFilterAttribute 来实现。这应该让你朝着正确的方向前进。您需要在评论的地方进行验证。

public class KeyAuthorizationAttribute : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        var guidValue = filterContext.RouteData.Values["guid"];
        if (guidValue != null) {
            Guid guid = new Guid(guidValue.ToString());
            bool notValid = true;
            //do validation
            //set notValid = false if authorization passes             

            if (notValid) {
                filterContext.Result = new HttpNotFoundResult();
            }
        }
    }
}

然后您将其应用于您的操作。

[KeyAuthorization]
public ActionResult Index() {
}

【讨论】:

  • Thankyouuuu BuildStarted 这就是我要找的
猜你喜欢
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-12
  • 2013-08-24
  • 2013-09-16
  • 2017-12-27
  • 1970-01-01
相关资源
最近更新 更多