【问题标题】:How do I use OnExceptionAspect to return ActionResult<IEnumerable<Model>>如何使用 OnExceptionAspect 返回 ActionResult<IEnumerable<Model>>
【发布时间】:2019-03-07 21:37:01
【问题描述】:

我有一个简单的ApiController,我试图捕捉并返回一个错误。这是一个快速的OnExceptionAspect 演示,但我遇到了一个障碍:我不知道如何将BadRequest 作为args.ReturnValue 返回。我认为它会比这更简单。这是我很长一段时间以来第一次使用 PostSharp,当然也是第一次使用 ASP.Net Core。

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

父控制器

[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】:

    问题似乎是基于实例的问题。我看到很多解决方案对于我需要的东西来说似乎过于复杂,所以我用最简单的方法来解决这个问题,直到找到更好的解决方案。我认为这是ActionResult&lt;T&gt; 在实例外部生成时返回类型特有的问题。出于单元测试的目的,这对于泛型来说似乎很简单,但由于这是运行时并且难以解决未知的返回类型,所以我选择了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;
    }
    

    我不确定这是正确的做法,但它适用于这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      • 1970-01-01
      • 2022-07-26
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多