【问题标题】:Best way to catch exception from rest service call using ajax使用ajax从rest服务调用中捕获异常的最佳方法
【发布时间】:2012-04-26 07:20:28
【问题描述】:

所以我正在使用 ajax 调用休息服务:

$("#loginsubmit").on('click', function () {
    showtooltip('Please wait...', false);
    $('#loginsubmit').attr("disabled", true);
    $.ajax({
        url: '@Utility.ConstructRestURL("Authenticate/Login")',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            client: {
                SessionID: '@Utility.GetSession(Utility.GetConfigString("ClientSessionID"))'
            },
            loginfo: {
                u: $("#loginusername").val(),
                p: $("#loginpassword").val()
            }
        }),
        success: function (response) {
            if (response.LoginResult.SessionID != null || response.LoginResult.UserID != null || response.LoginResult.SourceIP != null) {
                $.post('@Url.Action("SaveSession", "Auth")', response.LoginResult, function (msg) {
                    window.location.replace(msg.url);
                });
            } else {
                showtooltip('Login failed.', false);
                $('#loginsubmit').removeAttr("disabled");
            }
        },
        error: function (xhr, ajaxOptions, error) {
            showtooltip(xhr.status + ': ' + error, false);
            $('#loginsubmit').removeAttr("disabled");
        }
    });
});  

而且大部分服务都返回一个类对象:

    [WebInvoke(UriTemplate = "Login", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    public CModel.DTO.UserSessionDTO Login(CModel.Entities.ClientAuthentication client, CModel.DTO.LoginCredentials loginfo)
    {
        loginfo.i = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        CModel.Logic.IAuthenticate svc = CModel.Logic.ConfigAndResourceComponent.Container().Resolve<CModel.Logic.IAuthenticate>();
        CModel.Entities.UserSession session = svc.Login(client, loginfo);
        CModel.DTO.UserSessionDTO copied = Mapper.Map<CModel.Entities.UserSession, CModel.DTO.UserSessionDTO>(session);
        return copied;
    }  

public class UserSessionDTO
{
    public string SourceIP { get; set; }
    public string SessionID { get; set; }
    public long UserID { get; set; }
}  

发生异常时:

它在客户端显示“400: Bad request”错​​误(从 ajax 返回错误)。
我想让 ajax 显示的是异常消息“InvalidLogin”。

我的解决方案是这样,但我不知道该怎么做。

当抛出异常时,rest-project 将调用一些构造错误消息的方法,构造的消息将作为返回值。

如果你有更好的想法,请分享。

【问题讨论】:

    标签: c# ajax model-view-controller rest


    【解决方案1】:

    如果使用rest服务,则应使用WebFaultException,如果使用SOAP服务,则应使用FaultException

    【讨论】:

      猜你喜欢
      • 2012-10-19
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多