我提出,将try-catch代码里面每一个错误发生时被抛出我的自定义异常:
[Serializable]
public class CustomException : Exception
{
public CustomException() { }
public CustomException(string message)
: base(message) { }
public CustomException(string message, Exception innerException)
: base(message, innerException) { }
}
我有两个服务,REST和SOAP。 对于SOAP服务,我没有就扔我的自定义异常任何问题。 但在休息时,我遇到了很多困难。
下面是抛出WebFaultException的方法:
public static WebFaultException RestGetFault(ServiceFaultTypes fault)
{
ServiceFault serviceFault = new ServiceFault();
serviceFault.Code = (int)fault;
serviceFault.Description = ConfigAndResourceComponent.GetResourceString(fault.ToString());
FaultCode faultCode = new FaultCode(fault.ToString());
FaultReasonText faultReasonText = new FaultReasonText(serviceFault.Description);
FaultReason faultReason = new FaultReason(faultReasonText);
WebFaultException<ServiceFault> webfaultException = new WebFaultException<ServiceFault>(serviceFault, HttpStatusCode.InternalServerError);
throw webfaultException;
}
ServiceFault是一类在那里有我用它来把我需要的所有信息的一些属性。
我用这个方法抛出REST服务中的异常:
public static CustomException GetFault(ServiceFaultTypes fault)
{
string message = fault.ToString();
CustomException cusExcp = new CustomException(message, new Exception(message));
throw cusExcp;
}
样品REST服务(登录方法):
[WebInvoke(UriTemplate = "Login", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public Session Login(ClientCredentials client, LogCredentials loginfo)
{
try
{
// Login process
return copied;
}
catch (LogicClass.CustomException ex)
{
LogicClass.RestGetFault(LogicClass.EnumComponent.GetServiceFaultTypes(ex.Message));
throw ex;
}
}
MVC的部分:
控制器:
[HttpPost]
public ActionResult Login(LoginCredentials loginfo)
{
try
{
string param = "{\"client\":" + JSonHelper.Serialize<ClientAuthentication>(new ClientAuthentication() { SessionID = Singleton.ClientSessionID })
+ ", \"loginfo\":" + JSonHelper.Serialize<LoginCredentials>(loginfo) + "}";
string jsonresult = ServiceCaller.Invoke(Utility.ConstructRestURL("Authenticate/Login"), param, "POST", "application/json");
UserSessionDTO response = JSonHelper.Deserialize<UserSessionDTO>(jsonresult);
}
catch (Exception ex)
{
return Json(new
{
status = ex.Message,
url = string.Empty
});
}
return Json(new
{
status = "AUTHENTICATED",
url = string.IsNullOrWhiteSpace(loginfo.r) ? Url.Action("Index", "Home") : loginfo.r
});
}
我用ServiceCaller.Invoke调用REST API和检索响应:ServiceCaller.cs
public class ServiceCaller
{
public static string Invoke(string url, string parameters, string method, string contentType)
{
string results = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = method;
request.ContentType = contentType;
if (!string.IsNullOrEmpty(parameters))
{
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (HttpStatusCode.OK == response.StatusCode)
{
Stream responseStream = response.GetResponseStream();
int length = (int)response.ContentLength;
const int bufSizeMax = 65536;
const int bufSizeMin = 8192;
int bufSize = bufSizeMin;
if (length > bufSize) bufSize = length > bufSizeMax ? bufSizeMax : length;
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder(bufSize);
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
results = sb.ToString();
}
else
{
results = "Failed Response : " + response.StatusCode;
}
}
catch (Exception exception)
{
throw exception;
}
return results;
}
}
我期待的REST服务,在客户端返回此:
但最终,它总是返回此:
我该怎么办? 请帮忙。
编辑
这里是调用SOAP服务时的示例响应:
[FaultException: InvalidLogin]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9441823
你有没有看到“InvalidLogin”? 这就是我想看到从REST servivce的响应。
从REST示例响应:
[WebException: The remote server returned an error: (500) Internal Server Error.]
System.Net.HttpWebRequest.GetResponse() +6115971
我抛出一个WebFaultException
但是我收到一个WebException
。
如果我将无法获取对REST确切的错误信息,我会去SOAP。
感谢您的答案。