我在ASP.NET MVC中使用肌动蛋白过滤器,现在如果只有一个动作方法然后我没有问题但是当有2个同名方法时,协议就像http get和post那样不同然后如何我可以使用过滤器吗?
请指教!
行动方法: -
[httpget]
public actionresult home()
{
return view();
}
[httppost]
public actionresult home()
{
return null;
}
动作过滤器代码:
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
if (actionDescriptor.ControllerDescriptor.ControllerType == typeof(HomeController) &&
(actionDescriptor.ActionName.Equals("home")))
{
return new Filter[]
{
new Filter(this._actionFilter, FilterScope.Action, null)
};
}
return new Filter[] { };
}
public void OnActionExecuted( ActionExecutedContext filterContext)
{
try
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {{ "Controller", "xyz" },
{ "Action", "abc" } });
}
catch (Exception ex)
{
}
}
当我运行此代码时,我发现每次在httpget上运行此代码但我想在httppost方法上运行过滤器。
答案 0 :(得分:2)
您可以检查它是否具有HttpPost
属性,表示客户或HttPost
调用HttpoGet
:
public void OnActionExecuted( ActionExecutedContext filterContext)
{
try
{
var actionName = filterContext.ActionDescriptor.ActionName;
var actionParams = filterContext.ActionDescriptor.GetParameters
var actionParamsTypes = actionParams.Cast<ParameterDescriptor>()
.Select(x => x.ParameterType).ToArray();
var controllerType = filterContext.Controller.GetType();
var actionMethodInfo = controllerType.GetMethod(actionName,
actionParamsTypes,
null);
var IsHttpPost = actionMethodInfo.IsDefiend(typeof(HttpPostAttribute),false);
if(IsHttpPost) // checking if it is HttpPost
{
// do something
}
}
catch (Exception ex)
{
}
}
答案 1 :(得分:2)
在GetFilter方法中尝试使用它:
if (actionDescriptor.ControllerDescriptor.ControllerType == typeof(HomeController) &&
(actionDescriptor.ActionName.Equals("home")) && controllerContext.HttpContext.Request.HttpMethod == "POST" )