我有一個簡單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();}ActionResultExceptionAspectpublic 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]]'.
1 回答

楊__羊羊
TA貢獻1943條經驗 獲得超7個贊
該問題似乎是基于實例的問題。我看到很多解決方案對于我需要的東西來說似乎過于復雜,所以我用最簡單的方法來解決這個問題,直到找到更好的解決方案。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;
}
我絕不確定這是正確的方法,但它適用于這種情況。
- 1 回答
- 0 關注
- 128 瀏覽
添加回答
舉報
0/150
提交
取消