如何从ASP.NET中获取和设置自定义代码和消息?



我有一个端点的例子:

[HttpGet]
[Route("api/Portfolio")]
[ActionName("LoadNew")]
public async Task<List<RF_PORTFOLIO>> Get(CancellationToken cancellationToken)
{
List<RF_PORTFOLIO> ProfileList = new List<RF_PORTFOLIO>();
try
{
using (var context = new AMLPContext())
{
using (var manager = new PortfolioManager(context))
{
ProfileList = await manager.ProfileLoad(cancellationToken);
}
if (ProfileList.Count() == 0)
//Throw an exception with custom status code and message
}
}
catch (Exception ex)
{
//Catch the exception and return a response with the status code and message from the exception
}
return ProfileList;
}

在我的try-catch块中,我希望能够抛出一个异常,使用自定义状态码和消息来指示它是一个错误的请求,还是内部服务器错误等。

我很确定答案已经在stackoverflow中了!然而,以下的一些想法

这取决于你使用的是哪个框架

如果你使用ASP。净4。你可以使用ExceptionAttribute

public class ExceptionAttribute : System.Web.Http.Filters.ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
// handle the error
}
}
//// configuration.Filters.Add(new ExceptionAttribute()); this is how it's registered within HttpConfiguration

如果你使用ASP。净4。你可以使用ExceptionMiddleware

public class GlobalExceptionMiddleware : OwinMiddleware
{
//// middleware registered app.Use<GlobalExceptionMiddleware>(); => IAppBuilder
try
{
await Next.Invoke(context);
}
catch (Exception ex)
{
//// bug in webapi, response should be delivered but the client is already disconnected
if (ex is OperationCanceledException)
{
return;
}
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
}
}

如果你正在使用。net core,我还建议使用一个中间件组件,它也在第一位置注册

public class RequestMiddleware 
{
public RequestMiddleware(RequestDelegate next, ILogger log)
{
_next = next;
_Log = log;
}

public async Task Invoke(HttpContext context)
{
try {
await _next(context);
}
catch (Exception e)
{
//// do your error handling
}
}
}

最新更新