c# – 如何处理WebFaultException以返回CustomException?

c# – 如何处理WebFaultException以返回CustomException?,第1张

概述我做了我的自定义异常,每次发生错误时都会抛出try-catch: [Serializable]public class CustomException : Exception{ public CustomException() { } public CustomException(string message) : base(message) { } 我做了我的自定义异常,每次发生错误时都会抛出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服务,我在抛出自定义异常时没有任何问题.
但是在REST中,我遇到了很多困难.

以下是抛出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,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,buf.Length)) != 0)                    sb.Append(EnCoding.UTF8.GetString(buf,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服务的响应中看到的.
REST的示例响应:

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

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

解决方法 使用httpWebRequest(或JavaScript客户端)时,您的自定义异常对它们没有意义.只是http错误代码(如500内部服务器错误)和响应内容中的数据.

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

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

以上是内存溢出为你收集整理的c# – 如何处理WebFaultException以返回CustomException?全部内容,希望文章能够帮你解决c# – 如何处理WebFaultException以返回CustomException?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1243289.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存