So I’m calling rest services using 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");
}
});
});
And most of the services returns a class object:
[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; }
}
When an exception occurred:

It displays a “400: Bad request” error on the client side(returned error from ajax).
What I wanted for ajax to display is the exception message “InvalidLogin”.
My solution is this, but yet I don’t know how to do it.
When an exception is thrown, the rest-project will call some method that will construct the error message, and the constructed message will be the return value.
Or if you have the better idea, please share.
If using rest services,
WebFaultExceptionshould be used, and if using SOAP services, thenFaultException.