当前位置: 代码迷 >> JavaScript >> wcf 错误 抛出json格式的错误消息
  详细解决方案

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

热度:491   发布时间:2013-12-21 20:16:01.0
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);
}
  相关解决方案