我修改了默认路由规则,如下所示:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id= (string)null } // Parameter defaults
);
然后我可以将url设置为:
/Controller/Action/myParam
/Home/Index/MyParam
默认操作索引为:
public ActionResult Index(string id)
{
//....
}
我可以在行动中获得参数。但我想在OnActionExecuting中获得参数。我该怎么办?
答案 0 :(得分:22)
您应该可以通过以下方式访问它:
public override void OnActionExecuting(ActionExecutingContext filterContext) {
string id = filterContext.RouteData.Values["id"];
//...
}
答案 1 :(得分:0)
如果你想获得控制器,动作和所有参数,你可以这样做
var valuesStr = new StringBuilder();
if (ctx.RouteData != null && ctx.RouteData.Values != null)
foreach (var v in ctx.RouteData.Values)
valuesStr.AppendFormat("/{0}", v.Value);
_logger.Info("executing {0}", valuesStr.ToString());
which results in the whole path
结果:
"/Get/Customer/215840"
它也应该适用于多个参数。
答案 2 :(得分:0)
我使用以下代码来检索和比较传递给操作(.net core 3.1)的参数。
var vals = filterContext.ActionArguments.Values;
var fistobj = vals.FirstOrDefault();
var val = fistobj.GetType().GetProperties().FirstOrDefault(x => string.Equals(x.Name, "nameParameter", StringComparison.OrdinalIgnoreCase)).GetValue(fistobj);
if (val == null || val.ToString() != "value parameter")
{
filterContext.Result = new JsonResult(ExecuteResult.Fail(JanException.Parameter.API00001));
//base.OnActionExecuting(filterContext);
return;
}
有关OnActionExecuting和自定义属性InitializingActionAttribute的更多详细信息
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ControllerActionDescriptor controlActionDescriptor = (ControllerActionDescriptor)filterContext.ActionDescriptor;
var attributes = controlActionDescriptor.MethodInfo.CustomAttributes;
if (attributes.Any(a => a.AttributeType == typeof(InitializingActionAttribute)))
{
var vals = filterContext.ActionArguments.Values;
var fistobj = vals.FirstOrDefault();
var val = fistobj.GetType().GetProperties().FirstOrDefault(x => string.Equals(x.Name, "nameParameter", StringComparison.OrdinalIgnoreCase)).GetValue(fistobj);
if (val == null || val.ToString() != "value parameter")
{
filterContext.Result = new JsonResult(ExecuteResult.Fail(JanException.Parameter.API00001));
//base.OnActionExecuting(filterContext);
return;
}
}
base.OnActionExecuting(filterContext);
}
答案 3 :(得分:0)
可以从 OnActionExecuting 中的 ActionArguments 访问它。
public override void OnActionExecuting(ActionExecutingContext context) {
string id = context.ActionArguments["id"].ToString();
//...
}
答案 4 :(得分:-5)
从您的filterContext中,您应该能够获得所需的任何内容。
public class MyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Do your stuff here
}
}
[MyAttribute]
public ActionResult Index(string id)
{
//....
}