栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从启用AJAX的WCF服务返回错误详细信息

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从启用AJAX的WCF服务返回错误详细信息

编辑: 使用适当的自定义json错误处理程序更新了帖子

快速但不推荐的方式。

<serviceDebug includeExceptionDetailInFaults="true"/>

在您的服务行为中会为您提供所需的所有详细信息。

不错的方法

应用程序中的所有异常都将转换为,

JsonError
并使用进行序列化
DataContractJsonSerializer
。的
Exception.Message
是直接使用。FaultException提供FaultCode,而其他异常则以Faultpre
-1威胁为未知。

FaultException是使用HTTP状态代码400发送的,其他异常是HTTP代码500-内部服务器错误。这不是必需的,因为故障代码可用于确定它是否是未知错误。但是在我的应用程序中很方便。

错误处理程序

internal class CustomErrorHandler : IErrorHandler{    public bool HandleError(Exception error)    {        //Tell the system that we handle all errors here.        return true;    }    public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)    {        if (error is FaultException<int>)        { FaultException<int> fe = (FaultException<int>)error; //Detail for the returned value int faultCode = fe.Detail; string cause = fe.Message; //The json serializable object JsonError msErrObject = new JsonError { Message = cause, FaultCode = faultCode }; //The fault to be returned fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType())); // tell WCF to use JSON encoding rather than default XML WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json); // Add the formatter to the fault fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf); //Modify response HttpResponseMessageProperty rmp = new HttpResponseMessageProperty(); // return custom error pre, 400. rmp.StatusCode = System.Net.HttpStatusCode.BadRequest; rmp.StatusDescription = "Bad request"; //Mark the jsonerror and json content rmp.Headers[HttpResponseHeader.ContentType] = "application/json"; rmp.Headers["jsonerror"] = "true"; //Add to fault fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);        }        else        { //Arbitraty error JsonError msErrObject = new JsonError { Message = error.Message, FaultCode = -1}; // create a fault message containing our FaultContract object fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType())); // tell WCF to use JSON encoding rather than default XML var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json); fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf); //Modify response var rmp = new HttpResponseMessageProperty(); rmp.Headers[HttpResponseHeader.ContentType] = "application/json"; rmp.Headers["jsonerror"] = "true"; //Internal server error with exception mesasage as status. rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError; rmp.StatusDescription = error.Message; fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);        }    }    #endregion}

用于安装上述错误处理程序的Web行为

internal class AddErrorHandlerBehavior : WebHttpBehavior{    protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)    {        base.AddServerErrorHandlers(endpoint, endpointDispatcher);        //Remove all other error handlers        endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear();        //Add our own        endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new CustomErrorHandler());    }}

json错误数据协定

指定json错误格式。在此处添加属性以更改错误格式。

[DataContractFormat]public class JsonError{    [DataMember]    public string Message { get; set; }    [DataMember]    public int FaultCode { get; set; }}

使用错误处理程序

自托管

ServiceHost wsHost = new ServiceHost(new Webservice1(), new Uri("http://localhost/json"));ServiceEndpoint wsEndpoint = wsHost.AddServiceEndpoint(typeof(IWebservice1), new WebHttpBinding(), string.Empty);wsEndpoint.Behaviors.Add(new AddErrorHandlerBehavior());

App.config

<extensions>    <behaviorExtensions>      <add name="errorHandler"          type="WcfServiceLibrary1.ErrorHandlerElement, WcfServiceLibrary1" />    </behaviorExtensions>  </extensions>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/409896.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号