欢迎来到Doc100.Net免费学习资源知识分享平台!
您的位置:首页 > 程序异常 >

wcf 错误 抛出json格式的错误消息

更新时间: 2014-01-05 01:51:51 责任编辑: Author_N1

 

wcf 异常 抛出json格式的异常消息
//由于调用 ProvideFault 时,客户端处于阻塞状态,不要在这里进行长时间的操作
public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
{
	//避免敏感信息泄漏,例如:数据库配置, error包含的错误信息应该记录到服务器的日志中,不能显示给客户端
	// FaultException<int> e = new FaultException<int>(123, error.Message);
	DateTime now = DateTime.Now;
	time = now.ToString("yyyyMMddHHmmssfff", DateTimeFormatInfo.InvariantInfo);// "" + now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString();
	string errorMsg = "服务内部错误_" + time;
	// FaultException fe = new FaultException(errorMsg);
	// MessageFault mf = fe.CreateMessageFault();
	// msg = Message.CreateMessage(version, mf, fe.Action);

	//The fault to be returned
	msg = Message.CreateMessage(version, "", errorMsg, new DataContractJsonSerializer(typeof(string)));

	// tell WCF to use JSON encoding rather than default XML
	WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

	// Add the formatter to the fault
	msg.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

	//Modify response
	HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();

	// return custom error code, 400.
	rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
	rmp.StatusDescription = "Bad request";

	//Mark the jsonerror and json content
	rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
	rmp.Headers["jsonerror"] = "true";

	//Add to fault
	msg.Properties.Add(HttpResponseMessageProperty.Name, rmp);
}
上一篇:上一篇
下一篇:下一篇

 

随机推荐程序问答结果

 

 

如对文章有任何疑问请提交到问题反馈,或者您对内容不满意,请您反馈给我们DOC100.NET论坛发贴求解。
DOC100.NET资源网,机器学习分类整理更新日期::2014-01-05 01:51:51
如需转载,请注明文章出处和来源网址:http://www.doc100.net/bugs/t/2190/
本文WWW.DOC100.NET DOC100.NET版权所有。