0

所以我使用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 将调用一些构造错误消息的方法,构造的消息将作为返回值。

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

4

1 回答 1

0

如果使用 REST 服务,WebFaultException应该使用,如果使用 SOAP 服务,那么FaultException.

于 2012-04-30T01:44:58.603 回答