问题
i need a way to globally handle http errors inside my asp.net mvc web application. i did the following if the call to the action method is Ajax :-
$(document).ready(function () {
$(document).ajaxError(function (e, xhr, textStatus, errorThrown) {
if (xhr.status == 401)
window.location = "/Account/Login";
else if (xhr.status == 403 || xhr.status == 404)
alert(xhr.statusText, 'Error');
$(".loadingimage").hide();
});
where my action method looks as follow:-
[CheckUserPermissions(Action = "Edit", Model = "Skill")]
public async Task<ActionResult> DeleteKBLink(int? skillid,int? linktokbid)
{
if (skillid == null || linktokbid==null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var linktokb= await unitofwork.SkillRepository.FindLinkToKB(linktokbid.Value);
if (linktokb == null)
{
return new HttpStatusCodeResult(404, "The link has already been deleted.");
}
but i am not sure how i can handle the http errors in-case the request is not ajax ? currently i will be redirected to http not found page .. thnaks
回答1:
This solution works well for me...
[1]: Remove all 'customErrors' & 'httpErrors' from Web.config
[2]: Check 'App_Start/FilterConfig.cs' looks like this:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
[3]: in 'Global.asax' add this method:
public void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "ErrorPage");
routeData.Values.Add("action", "Error");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
Response.TrySkipIisCustomErrors = true;
IController controller = new ErrorPageController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
}
[4]: Add 'Controllers/ErrorPageController.cs'
public class ErrorPageController : Controller
{
public ActionResult Error(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
ViewBag.StatusCode = statusCode + " Error";
return View();
}
}
[5]: in 'Views/Shared/Error.cshtml'
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}
<h1 class="error">@(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>
//@Model.ActionName
//@Model.ContollerName
//@Model.Exception.Message
//@Model.Exception.StackTrace
来源:https://stackoverflow.com/questions/29279266/recommended-way-to-handle-http-errors-inside-my-asp-net-mvc-5-web-application