gpt4 book ai didi

asp.net-mvc - JsonResult和ActionResult的错误处理

转载 作者:行者123 更新时间:2023-12-03 07:49:27 25 4
gpt4 key购买 nike

ASP.NET MVC 5中,我试图扩展我的站点的常规错误处理,但是我很难一次覆盖ActionResultJsonResult。我知道JsonResult是从ActionResult转移过来的,但是当我返回ActionResult时,我只是给MVC一个View,对于JsonResult,我使用Javascript处理结果。

因此,在的情况下,其中Action的返回值是ActionResult,而Application_Error()返回JsonResult,即刚在 View 中打印的Json。在那种情况下你该怎么办?我宁愿让它重定向到错误页面或登录屏幕。我什至不知道我是否应该制作出能够处理json的javascript以便进行手动重定向的javascript,或者应该使用某些“内置” MVC机制。

在一个简化的示例中,我有两个Action's:

public ActionResult ShowPackages(PackagesViewModel packagesViewModel)
{
var model = PackageBalhelper.GetPackageViewModel(packagesViewModel);
return View(model);
}

[HttpPost]
public JsonResult GetDatatableRows(PackagesViewModel packagesViewModel)
{
var jsonResult = CreateJsonResult(packagesViewModel);
return jsonResult;
}

我到目前为止(来自 MSDN)
protected void Application_Error()
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
var requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;

// When the request is ajax the system can automatically handle a mistake with a JSON response. Then overwrites the default response
if (requestContext.HttpContext.Request.IsAjaxRequest())
{
httpContext.Response.Clear();
string controllerName = requestContext.RouteData.GetRequiredString("controller");
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(requestContext, controllerName);
ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);

var jsonResult = new JsonResult
{
Data = new
{
success = false,
serverError = "500"
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
jsonResult.ExecuteResult(controllerContext);
httpContext.Response.End();
}
else
{
LogHelper.WriteMessageToLog("In 'Application_Error'. Not an ajax request'.");
//httpContext.Response.Redirect("~/Error");
}
}
}

最佳答案

What are you supposed to do in that situation? I rather have it to redirect to errorpage or login screen.



您走在正确的轨道上。如果客户端期望服务器发出Json响应,我们绝对不希望返回View(重定向到自定义错误页面)。否则,它将破坏客户的逻辑。

此答案可能无法直接回答您的问题。但是,如果看到自己大量返回 JsonResult ,则可能要考虑在ASP.NET MVC 5中使用 Web API Controller

Web API 2.1支持 GlobalExceptionHandler ,您可以在其中自定义在发生未处理的应用程序期望时发送的Http响应。

就我而言,我将 Angular与ASP.NET MVC和Web API一起使用。因此,我必须为Ajax请求以Json格式返回未处理的异常。

WebApiExceptionHandler.cs

如果您的应用程序引发自定义异常,您甚至可以在此处过滤它们,并返回适当的消息。
public class WebApiExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var exception = context.Exception;
var httpException = exception as HttpException;
if (httpException != null)
{
context.Result = new WebApiErrorResult(context.Request,
(HttpStatusCode) httpException.GetHttpCode(), httpException.Message);
return;
}
/*if (exception is MyCustomException)
{
context.Result = new WebApiErrorResult(context.Request,
HttpStatusCode.NotFound, exception.Message);
return;
}*/
context.Result = new WebApiErrorResult(context.Request,
HttpStatusCode.InternalServerError,
"An error occurred while processing your request.");
}
}

WebApiErrorResult.cs
public class WebApiErrorResult : IHttpActionResult
{
private readonly string _errorMessage;
private readonly HttpRequestMessage _requestMessage;
private readonly HttpStatusCode _statusCode;

public WebApiErrorResult(
HttpRequestMessage requestMessage,
HttpStatusCode statusCode,
string errorMessage)
{
_requestMessage = requestMessage;
_statusCode = statusCode;
_errorMessage = errorMessage;
}

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_requestMessage.CreateErrorResponse(_statusCode, _errorMessage));
}
}

WebApiConfig.cs

最后,我们向框架注册我们的自定义异常处理程序。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });

config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionHandler());

config.Filters.Add(new AuthorizeAttribute());
}
}

关于asp.net-mvc - JsonResult和ActionResult的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001097/

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