gpt4 book ai didi

asp.net-mvc - 我可以从操作过滤器获取操作的返回类型吗?

转载 作者:行者123 更新时间:2023-12-02 12:19:50 26 4
gpt4 key购买 nike

我有一个 ASP.NET MVC 2 应用程序,我正在其中创建自定义操作筛选器。该过滤器位于应用程序中的 Controller 上,并从数据库中验证该功能当前是否可用。

Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
Try
' Check controller name against database.
Dim controllerName = filterContext.Controller.GetType().Name
controllerName = controllerName.Remove(controllerName.Length - 10)
' Look up availability.
Dim available As Boolean = _coreService.GetControllerAvailability(controllerName)
If Not available Then
' Redirect to unavailable notice.
filterContext.Result = New RedirectResult("/Home/Unavailable/")
End If
Catch ex As Exception
_eventLogger.LogWarning(ex, EventLogEntryType.Error)
Throw
End Try
End Sub

我的问题是,根据请求的操作,我需要将用户重定向到返回 View 、部分 View 或 JSON 的操作。

给定 ActionExecutingContext,我可以找出最初请求的操作的返回类型是什么吗?

编辑:

好的,我已经接近了,但还有另一个问题。

Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
Try
' Check controller name against database.
Dim controllerName = filterContext.Controller.GetType().Name
Dim shortName = controllerName.Remove(controllerName.Length - 10)
' Look up availability.
Dim available As Boolean = _coreService.GetControllerAvailability(shortName)
If Not available Then
' find out what type is expected to be returned
Dim actionName As String = filterContext.ActionDescriptor.ActionName
Dim controllerType = Type.GetType("Attenda.Stargate.Web." & controllerName)
Dim actionMethodInfo = controllerType.GetMethod(actionName)
Dim actionReturnType = actionMethodInfo.ReturnType.Name

Select Case actionReturnType
Case "PartialViewResult"
filterContext.Result = New RedirectResult("/Home/UnavailablePartial/")
Case "JsonResult"
filterContext.Result = New RedirectResult("/Home/UnavailableJson/")
Case Else
filterContext.Result = New RedirectResult("/Home/Unavailable/")
End Select

End If
Catch ex As Exception
_eventLogger.LogWarning(ex, EventLogEntryType.Error)
Throw
End Try
End Sub

我可以使用反射来查找操作方法的返回类型。我的问题是 Controller 上是否有以下方法:

Public Function Create() As ViewResult
Return View()
End Function

<AcceptVerbs(HttpVerbs.Post)>
Public Function Create(values as FormCollection) As ViewResult
' Do stuff here
End Function

我抛出了 AmbigeousMatchException。

根据我在 OnActionExecuting 方法中获得的信息,是否可以更精确地确定正在调用的重载?

最佳答案

我基于此创建了一个 AuthenticationFilterAttribute,它根据类型返回不同的结果:

    /// <summary>
/// Access to the action will be blocked if the user is not logged in.
/// Apply this to the controller level or individual actions as an attribute.
/// </summary>
public class AuthenticationFilterAttribute : ActionFilterAttribute
{
protected const string InvalidAccess = "Invalid access";

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Find out if the user is logged in:
Controller controller = (Controller)filterContext.Controller;
if (!controller.User.Identity.IsAuthenticated)
{
switch (GetExpectedReturnType(filterContext).Name)
{
case "JsonResult":
var jsonResult = new JsonResult();
jsonResult.Data = new { Error = true, ErrorMessage = InvalidAccess };
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result = jsonResult;
break;

// Assume same behaviour as ActionResult
default:
var actionResult = new ContentResult();
actionResult.Content = InvalidAccess;
filterContext.Result = actionResult;
break;
}
}
}

private Type GetExpectedReturnType(ActionExecutingContext filterContext)
{
// Find out what type is expected to be returned
string actionName = filterContext.ActionDescriptor.ActionName;
Type controllerType = filterContext.Controller.GetType();
MethodInfo actionMethodInfo = default(MethodInfo);
try
{
actionMethodInfo = controllerType.GetMethod(actionName);
}
catch (AmbiguousMatchException ex)
{
// Try to find a match using the parameters passed through
var actionParams = filterContext.ActionParameters;
List<Type> paramTypes = new List<Type>();
foreach (var p in actionParams)
{
paramTypes.Add(p.Value.GetType());
}

actionMethodInfo = controllerType.GetMethod(actionName, paramTypes.ToArray());
}

return actionMethodInfo.ReturnType;
}
}

关于asp.net-mvc - 我可以从操作过滤器获取操作的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2865061/

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