在webApi控制器中实现Onfailure

Implement Onfailure in webApi controller

本文关键字:实现 Onfailure 控制器 webApi      更新时间:2023-09-26

我有一个Web Api,其中我有以下代码

                   @{
                    AjaxOptions addAjaxOpts = new AjaxOptions
                    {
                        // options will go here
                        OnSuccess = "getData", 
                        OnFailure="selectView('add')",
                        HttpMethod = "Post",
                        Url = "/api/AccountManage/CreateAccount"
                    };
                }

在控制器中:

[HttpPost]
        public void CreateAccount(CollaborateurModel item)
        {
        try{}
        catch{
             // return failure
             }
         }           

我需要实现failure part来执行OnFailure方法。

那么我该如何完成这个任务呢?

可以使用Json Result (MSDN ref.)

片段的例子:

[HttpPost]
public ActionResult CreateAccount(CollaborateurModel item)()
{
    try{
      //do operations that may fail
      var response = new { Success = true};
      return Json(response );
    }catch{
      var errorResponse= new { Success = false, ErrorMessage = "error"};
      return Json(errorResponse);
    }
}
然后在客户端使用JQuery调用控制器:

$(function () {
   $(".test-link").click(function (e) {
      $.post("controllerName/CreateAccount", function (data) {
        if (data.Success == true) {
           alert("Success");
         }
         else {alert(data.ErrorMessage);}
       });
       return false;
    }).fail(function() {
      alert( "error" );
     });
});

Jquery的fail函数将处理您可能与客户端-服务器之间的通信问题。

更多关于JQuery的信息,你可以在这里找到

根据所需的响应状态码,可以使用BadRequest、NotFound或InternalServerError结果类。它们都有一个构造函数,该构造函数有一个可选参数,用于发送错误消息。

[HttpPost]
public IHttpActionResult CreateAccount(CollaborateurModel item)
{
    try
    {
        // Do your thing
    }
    catch
    {
        // Return a HTTP 400 result
        return BadRequest("This is an error message");
    }
}