gpt4 book ai didi

c# - 实现 IActionFilter

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:27 25 4
gpt4 key购买 nike

我正在构建以下过滤器:

public class TestflowFilter : FilterAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext filterContext)
{
var profileId = int.Parse(ClaimsPrincipal.Current.GetClaimValue("UserId"));
var appId = int.Parse(filterContext.RouteData.Values["id"].ToString());

if (profileId != 0 && appId != 0)
{
if (CheckIfValid(profileId, appId))
{
// redirect
filterContext.Result = // url to go to
}
}
}

public void OnActionExecuting(ActionExecutingContext filterContext)
{
}

}

我实际上只需要 OnActionExecuted,但由于 IActionFilter 是一个接口(interface),我必须同时实现它们。如果我不需要任何事情发生,是否可以将 OnActionExecuting 留空,或者我是否需要调用 MVC 始终运行的基本版本?

同样在 OnActionExecuted 方法中,如果 CheckIfValidtrue,我会重定向用户,但如果不是,我什么都不做。这样可以吗,还是我需要在 filterContext 上设置一些属性。

最佳答案

I actually only need OnActionExecuted, but since IActionFilter is an interface I have to implement them both. Is it ok to leave OnActionExecuting blank if I don't need anything to happen, or do I need to call a base version that MVC always runs?

在这种情况下,将方法主体留空是完全可以接受的。看起来不错!

Also In the OnActionExecuted method if the CheckIfValid is true I redirect the user, but if not I don't do anything, is that ok or do I need to set some property on the filterContext instead.

您的过滤器没问题。 MVC 确实提供了一个名为 ActionFilterAttribute 的不同抽象基类,它实现了这些接口(interface),供您根据需要覆盖。你有一个很好的概述can read about here .如果您从该类派生,您的过滤器属性代码可以简化一点:

public class TestflowFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var profileId = int.Parse(ClaimsPrincipal.Current.GetClaimValue("UserId"));
var appId = int.Parse(filterContext.RouteData.Values["id"].ToString());

if (profileId != 0 && appId != 0)
{
if (CheckIfValid(profileId, appId))
{
// redirect
filterContext.Result = // url to go to
}
}
}
}

关于c# - 实现 IActionFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36779196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com