gpt4 book ai didi

c# - ExceptionHandling : If controller method returns json then return json, if View then return Redirect

转载 作者:行者123 更新时间:2023-11-30 15:14:09 29 4
gpt4 key购买 nike

我想实现这样的目标:

如果在返回 Json 的方法中抛出异常,则返回 new Json(new { success = false, error = "unknown"});

但如果方法返回 View 则返回 Redirect

public async Task Invoke(HttpContext ctx)
{
try
{
await next(ctx);
}
catch (Exception ex)
{
HandleException(ctx, ex);
}
}

private static void HandleException(HttpContext context, Exception ex)
{
// some logger
LoggerService.Log(ex);

context.Response.Redirect("/Error/ErrorPage");
}

如何确定请求发送到哪里?我的意思是如何获取请求发送到的方法类型?

因为我想做一些类似typeof(targetMethod) 的事情来确定它是否是例如JsonResult

最佳答案

听起来您正在尝试处理 Action 方法抛出的异常。如果是这样的话,ASP.NET Core 有一个内置的 IExceptionFilter , 这适用于:

A filter that runs after an action has thrown an Exception.

为了实现您的目标,创建一个CustomExceptionFilter:

public class CustomExceptionFilter : IExceptionFilter
{
private ILogger<CustomExceptionFilter> _logger;

public CustomExceptionFilter(ILogger<CustomExceptionFilter> logger)
{
this._logger = logger;
}

public void OnException(ExceptionContext context)
{
var ex = context.Exception;
var c = (ControllerActionDescriptor) context.ActionDescriptor;

if(c == null){
context.Result = new StatusCodeResult(500);
} else if (typeof(JsonResult) == c.MethodInfo.ReturnType) {
context.Result = new JsonResult(new { success = false, error = "unknown" });
} else {
// Redirect
this._logger.LogCritical(ex,ex.Message);
context.Result = new RedirectResult("/Error/ErrorPage");
}
}
}

并如下注册这个过滤器:

services.AddMvc(opts => {
opts.Filters.Add(typeof(CustomExceptionFilter));
});

它对我来说很好。

关于c# - ExceptionHandling : If controller method returns json then return json, if View then return Redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55916128/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com