如何使用OnExceptionAspect返回ActionResult >

问题描述 投票:1回答:1

我有一个简单的ApiController,我试图抓住并返回错误。这是一个快速的OnExceptionAspect演示,但我遇到了障碍:我无法弄清楚如何返回BadRequest作为args.ReturnValue。我认为这比这更简单。这是我第一次在很长一段时间内使用PostSharp,当然也是第一次使用ASP.Net Core。

注意:我在上下文中有一个错误的连接字符串来强制快速错误(未显示)。

ParentController

[HttpGet("Get/{studentId}")]
[ActionResultExceptionAspect(StatusCode = HttpStatusCode.BadRequest)]
public ActionResult<IEnumerable<ParentModel>> RetrieveParents(string studentId)
{
    var query = Context.ParentViews
        .Where(x => x.StudentID == studentId)
        .Select(s => EntityMapper.MapFromEntity(s));

    return query.ToArray();
}

ActionResultExceptionAspect

public override void OnException(MethodExecutionArgs args)
{
    args.FlowBehavior = FlowBehavior.Return;
    args.ReturnValue = ((StudentControllerBase)args.Instance).BadRequest();
}

我得到一个错误:

System.InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Mvc.BadRequestResult' to type 'Microsoft.AspNetCore.Mvc.ActionResult`1[System.Collections.Generic.IEnumerable`1[Student.Models.ParentModel]]'.
c# .net-core postsharp asp.net-apicontroller
1个回答
1
投票

问题似乎是基于实例的问题。我看到很多解决方案对于我需要的东西看起来过于复杂,所以我采用最简单的方法来解决这个问题,直到找到更好的东西。我已经看到这是一个特定于ActionResult<T>返回类型的问题,只要在实例外生成。对于单元测试而言,这对于泛型似乎很简单,但由于这是运行时并且难以解决未知的返回类型,因此我选择了Activator.CreateInstance

我新的OnException方法是:

public override void OnException(MethodExecutionArgs args)
{
    var methType = ((MethodInfo)args.Method).ReturnType;

    args.ReturnValue = Activator.CreateInstance(methType, ((ControllerBase)args.Instance).BadRequest());
    args.FlowBehavior = FlowBehavior.Return;
}

我无法确定这是正确的方法,但它适用于此实例。

© www.soinside.com 2019 - 2024. All rights reserved.