I'm working on Asp.net MVC project as a single page application for error handling.
I want to return json data from Application_Error
method in global.asax
to UI and show it by jQuery or call a controller and return partialView.
I don't want to refresh the page or redirect it to Error page.
Asked
Active
Viewed 3,814 times
2

Hakan Fıstık
- 16,800
- 14
- 110
- 131

Mehrdad Bahrainy
- 1,597
- 1
- 14
- 20
-
Use an action filter instead. – asawyer Oct 29 '12 at 11:57
-
possible duplicate of [Need some help with a custom ASP.NET MVC IExceptionFilter](http://stackoverflow.com/questions/1419414/need-some-help-with-a-custom-asp-net-mvc-iexceptionfilter) – asawyer Oct 29 '12 at 11:58
-
1Look at this question: http://stackoverflow.com/questions/4707755/asp-net-mvc-ajax-error-handling – webdeveloper Oct 29 '12 at 12:32
2 Answers
2
here is the way to go
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
// if the error is NOT http error, then stop handling it.
if (!(exception is HttpException httpException))
return;
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
Response.Clear();
Response.TrySkipIisCustomErrors = true;
Server.ClearError();
Response.ContentType = "application/json";
Response.StatusCode = 400;
JsonResult json = new JsonResult
{
Data = exception.Message
};
json.ExecuteResult(new ControllerContext(Request.RequestContext, new BaseController()));
}
}

Hakan Fıstık
- 16,800
- 14
- 110
- 131
1
//Write This code into your global.asax file
protected void Application_Error(Object sender, EventArgs e)
{
var ex = Server.GetLastError();
//We check if we have an AJAX request and return JSON in this case
if (IsAjaxRequest())
{
Response.Write(JsonConvert.SerializeObject(new
{
error = true,
message = "Exception: " + ex.Message
})
);
}
}
private bool IsAjaxRequest()
{
//The easy way
bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
|| ((Request.Headers != null)
&& (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
//If we are not sure that we have an AJAX request or that we have to return JSON
//we fall back to Reflection
if (!isAjaxRequest)
{
try
{
//The controller and action
string controllerName = Request.RequestContext.
RouteData.Values["controller"].ToString();
string actionName = Request.RequestContext.
RouteData.Values["action"].ToString();
//We create a controller instance
DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
Controller controller = controllerFactory.CreateController(
Request.RequestContext, controllerName) as Controller;
//We get the controller actions
ReflectedControllerDescriptor controllerDescriptor =
new ReflectedControllerDescriptor(controller.GetType());
ActionDescriptor[] controllerActions =
controllerDescriptor.GetCanonicalActions();
//We search for our action
foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
{
if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
{
//If the action returns JsonResult then we have an AJAX request
if (actionDescriptor.MethodInfo.ReturnType
.Equals(typeof(JsonResult)))
return true;
}
}
}
catch
{
}
}
return isAjaxRequest;
}
//Write this code in your ajax function in html file
<script type="text/javascript">
$.ajax({
url: Url
type: 'POST',
data: JSON.stringify(json_data),
dataType: 'json',
cache: false,
contentType: 'application/json',
success: function (data) { Successfunction(data); },
error: function (xhr, ajaxOptions, thrownError) {
var obj = JSON.parse(xhr.responseText);
if (obj.error) {
show_errorMsg(obj.message);
}
}
});
</script>

Suleman John
- 11
- 3