如何处理WebFaultException以返回CustomException? [英] How to Handle WebFaultException to return CustomException?

查看:68
本文介绍了如何处理WebFaultException以返回CustomException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做出了自定义异常,每次发生错误时都会在try-catch中抛出该异常:

I made my custom exception that will be thrown inside try-catch each time an error is occured:

[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服务,抛出自定义异常没有任何问题. 但是在REST中,我遇到了很多困难.

I have two services, REST and SOAP. For SOAP services, I don't have any problem on throwing my custom exception. But in REST, I encountered a lot of difficulties.

这是引发WebFaultException的方法:

Here is the method for throwing a 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是一个类,其中具有一些属性,我可以使用这些属性来放置我需要的所有信息.

ServiceFault is a class where it has some properties which I use to put all information I need.

我使用此方法在REST服务内部引发异常:

I use this method to throw an exception inside REST service:

    public static CustomException GetFault(ServiceFaultTypes fault)
    {
        string message = fault.ToString();
        CustomException cusExcp = new CustomException(message, new Exception(message));
        throw cusExcp;
    }  

示例REST服务(登录方法):

A sample REST Service (log in method):

    [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

I use ServiceCaller.Invoke to call REST API and retrieve the response: 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服务在客户端将其返回:

I am expecting the REST service to return this on client side:

但是最后,它总是返回:

But in the end, it always return this:

我该怎么办?请帮忙.

编辑

这是调用soap服务时的示例响应:

Here is the sample response when calling the soap service:

[FaultException: InvalidLogin]
   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9441823  

您看到"InvalidLogin"了吗?这就是我希望在REST服务的响应中看到的内容.
REST的示例响应:

Did you see the "InvalidLogin" ? That is what I want to see on the response from REST servivce.
Sample response from REST:

[WebException: The remote server returned an error: (500) Internal Server Error.]
   System.Net.HttpWebRequest.GetResponse() +6115971  

我抛出了WebFaultException,但收到了WebException.
如果我无法在REST上获取确切的错误消息,我将使用SOAP.
感谢您的回答.

I throw a WebFaultException but I receive a WebException.
If I won't be able to fetch the exact error message on REST, I will go for SOAP.
Thanks for the answers.

推荐答案

使用HttpWebRequest(或Javascript客户端)时,您的自定义异常对它们没有意义.只是Http错误代码(例如 500 Internal server error )和响应内容中的数据.

When using HttpWebRequest (or a Javascript client), your custom exception has no meaning for them. Just Http error codes(like 500 Internal server error) and the data in the response's content.

因此,您必须自己处理异常.例如,如果捕获WebException,则可以根据服务器配置以Xml或Json格式读取内容(错误消息).

So you have to handle the exception by yourself. For example, if you catch WebException you can read the content(the error message) in Xml or Json format depending on your server configurations.

catch (WebException ex)
{
    var error = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
    //Parse your error string & do something
}

这篇关于如何处理WebFaultException以返回CustomException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆