【发布时间】: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