【问题标题】:ASP.NET MVC - An attribute argument must be a constant expressionASP.NET MVC - 属性参数必须是常量表达式
【发布时间】:2017-02-24 10:16:12
【问题描述】:

我正在尝试创建一个自定义属性来验证我的 MVC 5 应用程序的每个操作方法中的会话状态。

这是自定义属性的代码。

[AttributeUsage(AttributeTargets.Method)]
public class CheckSession : ActionFilterAttribute
{
    public string SessionKey { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionParameters.ContainsKey(SessionKey))
        {
            string value = filterContext.ActionParameters[SessionKey] as string;

            if ((string)filterContext.HttpContext.Session[value] == null)
            {
                var control = filterContext.Controller as Controller;

                if (control != null)
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new System.Web.Routing.RouteValueDictionary
                        {
                            {"controller", "Home"},
                            {"action", "Error"}, 
                            {"area", ""}
                        }
                    );
                }
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }
    }
}

我正在使用的会话密钥的常量:

public static class SessionKeysConstants
{
    public static readonly string SMSNotificationsSearchClient = "SMSNotificationsSearchClient";
}

我正在使用这样的自定义属性:

[CheckSession(SessionKey = SessionKeysConstants.SMSNotificationsSearchClient)]
public ActionResult Index()
{
    // You need a session to enter here!
    return View("Index");
}

并得到以下错误:

属性参数必须是常量表达式,typeof 表达式 或属性参数类型的数组创建表达式

我不明白为什么,我使用的是常量,并且只能将值字符串直接分配给 SessionKey 参数。

【问题讨论】:

  • 它需要是public const string SMSNotificationsSearchClient = "SMSNotificationsSearchClient";(静态并不意味着恒定)
  • 它不起作用,我遇到了同样的错误。
  • 那你没有使用上面的代码(我刚刚测试过,没问题)
  • 我还以为是public readonly string SMSNotificationsSearchClient = "SMSNotificationsSearchClient";,没有static关键字,你编辑了文字吗?
  • 是的,它确实有效!

标签: asp.net-mvc custom-attributes


【解决方案1】:

属性参数仅限于以下类型的常量值:

  • 简单类型(bool、byte、char、short、int、long、float 和 double)
  • 字符串
  • System.Type
  • 枚举
  • object(object类型的属性参数的参数必须是上述类型之一的常量值。)
  • 上述任何类型的一维数组

参考:https://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx

如果您将SessionKeysConstants 定义为枚举,则可以解决您的问题。对于那个枚举,一个命名常量是SMSNotificationsSearchClient

正如@StephenMuecke 上面所说,您也可以将字符串设为 const。

我更喜欢枚举,如果您正在寻找数据注释(例如),这在某种程度上是一个标准:https://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx

基本上,您的SessionKeysConstants 是命名常量的枚举,根据定义,它是enum,但这只是我个人的看法。

【讨论】:

  • 这不是一个常数。
猜你喜欢
  • 1970-01-01
  • 2013-02-09
  • 2014-11-13
  • 2016-01-05
  • 1970-01-01
  • 2011-12-10
相关资源
最近更新 更多