从MVC控制器返回的自定义错误jQuery的ajax调用 [英] Returning custom error from mvc controller to jquery ajax call

查看:106
本文介绍了从MVC控制器返回的自定义错误jQuery的ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所试图做的是从一个asp.net mvc4控制器自定义错误传递给jquery.ajax()调用。所以我写了一个自定义错误过滤器:

 公共类FormatExceptionAttribute:HandleErrorAttribute
{
    公共覆盖无效onException的(ExceptionContext filterContext)
    {
        如果(filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result =新JsonResult()
            {
                的ContentType =应用/ JSON
                数据=新
                {
                    名称= filterContext.Exception.GetType()名,
                    消息= filterContext.Exception.Message,
                    调用堆栈= filterContext.Exception.StackTrace
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };            filterContext.ExceptionHandled = TRUE;
            filterContext.HttpContext.Response.Status code = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = TRUE;
        }
        其他
        {
            base.OnException(filterContext);
        }
    }
 }

和我有表演把它注册为一个全球性的过滤器:

  GlobalFilters.Filters.Add(新FormatExceptionAttribute());

下面我mvc4视图定义我的Ajax调用(请注意,任务就像是一个字符串/ myController的/ MyAction /):

 函数loadData(任务){
     阿贾克斯({
         网址:任务,
         输入:POST,
         数据类型:JSON,
         的contentType:应用/ JSON的;字符集= UTF-8
     })。然后(功能(数据){
         $(数据).MAP(函数(一,项目){
             addNewElement(项目);
         })
     },
             功能(XHR){
                 尝试{
                     //一个try / catch被推荐为错误处理程序
                     //可能发生在许多事件和可能没有
                     //来自服务器的JSON响应
                     VAR JSON = $ .parseJSON(xhr.responseText);
                     警报(json.errorMessage);
                 }赶上(E){
                     警报('坏事发生');
                 }
             });
 };

所以MyAction在myController的如下所示:

  [HttpPost]
    公众的ActionResult MyAction()
    {
        尝试
        {
            VAR dataCollection =(动态)空;            使用(ConfigContext上下文=新ConfigContext())
            {
                dataCollection = context.MyItems.Where(I => i.TypeId == 1).AsEnumerable()排序依据(K => k.Name)。选择(W =>新建
                    {
                        别名=的String.Format({0} - {1},Resources.Constants preFIX,w.Id)
                        名称= w.Name,
                        说明= w.Desc
                    })ToArray的()。
            }            返回JSON(dataCollection);
        }
        赶上(异常前)
        {            //我想ex.Message返回jquery.ajax()调用
            JsonResult jsonOutput = JSON(
             新
             {
                 回复=新
                 {
                     状态=无法在MyAction。
                     消息=错误:+ ex.Message
                 }
             });            返回jsonOutput;
        }
    }

由于某些原因,在jquery.ajax()调用我没有收到由控制器(服务器端)发送ex.message误差和jquery.ajax()试图转换使用到JSON时:

  VAR JSON = $ .parseJSON(xhr.responseText);

抛出一个异常说这是不是一个JSON结果所以在jquery.ajax在卡位体进入:

 }赶上(E){
     警报('坏事发生');
 }

所以我想什么做的是:


  1. 返回来自控制器的ex.message到jquery.ajax()
    呼叫。

  2. 此外(不错的),而不是注册
    自定义错误过滤上述作为一个全球性的过滤器
    的global.asax.cs,我想只有它适用于那些特定的
    由Ajax调用调用的控制器/行动。

  3. 同样(也许这将是更好地打开另一个线程),字符串连接(的String.format)在MyAction控制器抛出,当我部署/发布我的web应用程序作为IIS默认Web站点下的应用程序,但一个例外但它是工作确定为一个独立的网站,在部署时,它(不抛出任何错误)。我使用嵌入到SQL Server精简版SQLCE。据我知道这是不支持级联,但我解决了这个应用AsEnumerable()。它可以作为一个单独的网站部署Web应用程序时,但在默认Web站点的应用程序部署时,这是行不通的。这里任何想法?


解决方案

  [HttpPost]
公众的ActionResult UpdateUser两个(UserInformation模型){
    如果(!UserIsAuthorized())
        返回新的HTTPStatus codeResult(401,自定义错误消息1); //未经授权
    如果(!model.IsValid)
        返回新的HTTPStatus codeResult(400,自定义错误消息2); // 错误的请求
    //等等。
}
 $阿贾克斯({
                键入:POST,
                网址:/ mymvccontroller / UpdateUser两个
                数据:$('#MyForm的')序列化()。
                错误:功能(XHR,状态,错误){
                    的console.log(错误); //应该是你自定义错误消息
                },
                成功:功能(数据){                }
            });

What I am trying to do is to pass a custom error from an asp.net mvc4 controller to a jquery.ajax() call. So I have written a custom error filter:

public class FormatExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult()
            {
                ContentType = "application/json",
                Data = new
                {
                    name = filterContext.Exception.GetType().Name,
                    message = filterContext.Exception.Message,
                    callstack = filterContext.Exception.StackTrace
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
        else
        {
            base.OnException(filterContext);
        }
    }
 }

And I have register it as a global filter by performing:

GlobalFilters.Filters.Add(new FormatExceptionAttribute());

Below my ajax call defined at my mvc4 view (Note that task is a string like "/MyController/MyAction/"):

 function loadData(task) {
     ajax({
         url: task,
         type: 'POST',
         dataType: 'json',
         contentType: "application/json; charset=utf-8"
     }).then(function (data) {
         $(data).map(function (i, item) {
             addNewElement(item);
         })
     },
             function (xhr) {
                 try {
                     // a try/catch is recommended as the error handler
                     // could occur in many events and there might not be
                     // a JSON response from the server
                     var json = $.parseJSON(xhr.responseText);
                     alert(json.errorMessage);
                 } catch (e) {
                     alert('something bad happened');
                 }
             });
 };

So MyAction in Mycontroller looks like the following:

    [HttpPost]
    public ActionResult MyAction()
    {
        try
        {
            var dataCollection = (dynamic)null;

            using (ConfigContext context = new ConfigContext())
            {
                dataCollection = context.MyItems.Where(i=> i.TypeId == 1).AsEnumerable().OrderBy(k => k.Name).Select(w => new
                    {
                        Alias = string.Format("{0}-{1}", Resources.Constants.Prefix, w.Id),
                        Name = w.Name,
                        Desc = w.Desc
                    }).ToArray();
            }

            return Json(dataCollection);
        }
        catch (Exception ex)
        {

            // I want to return ex.Message to the jquery.ajax() call
            JsonResult jsonOutput = Json(
             new
             {
                 reply = new
                 {
                     status = "Failed in MyAction.",
                     message = "Error: " + ex.Message
                 }
             });

            return jsonOutput;
        }
    }

For some reason, in the jquery.ajax() call I am not getting the ex.message error sent by the controller (server side) and in jquery.ajax() when trying to convert to json using:

var json = $.parseJSON(xhr.responseText);

an exception is thrown saying it is not a json result so in the jquery.ajax is entering in the catch body:

 } catch (e) {
     alert('something bad happened');
 }

So What I would like to do is:

  1. Returning the ex.message from the controller to the jquery.ajax() call.
  2. Additionally (nice to have), instead of registering the custom error filter above indicated as a global filter in global.asax.cs, I would like to only apply it to those particular controller/actions that are invoked by ajax calls.
  3. Also (maybe it would be better to open another thread), string concatenation (String.format) in MyAction in the controller throws an exception when I deploy/publish my web app as an application under the default web site on IIS but however it is working ok (not throwing any error) when deploying it as a separate web site. I am using an SQL Server compact edition SQLCe embedded. As far as i know it is not supporting concatenation but i solved this by applying AsEnumerable(). It works when deploying web app as a separate web site but it does not work when deploying it as an application under default web site. Any ideas here?

解决方案

[HttpPost]
public ActionResult UpdateUser(UserInformation model){
    if (!UserIsAuthorized())
        return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized
    if (!model.IsValid)
        return new HttpStatusCodeResult(400, "Custom Error Message 2"); // Bad Request
    // etc.
}


 $.ajax({
                type: "POST",
                url: "/mymvccontroller/UpdateUser",
                data: $('#myform').serialize(),
                error: function (xhr, status, error) {
                    console.log(error); //should be you custom error message
                },
                success: function (data) {

                }
            });

这篇关于从MVC控制器返回的自定义错误jQuery的ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆