【发布时间】: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