Taylohtio/GeneralSSO/GeneralSSO.Server/CodeFiles/Infrastructure/WCF/JsonErrorHandler.cs

42 lines
1.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
namespace Taloyhtio.GeneralSSO.Server.CodeFiles.Infrastructure.WCF
{
// See http://stackoverflow.com/questions/1149037/how-to-make-custom-wcf-error-handler-return-json-response-with-non-ok-http-code
public class JsonErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
// yes, we handled this exception
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
// create message
var jsonError = new JsonErrorDetails { Message = error.Message, ExceptionType = error.GetType().FullName };
fault = Message.CreateMessage(version, "", jsonError, new DataContractJsonSerializer(typeof(JsonErrorDetails)));
// 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
{
StatusCode = HttpStatusCode.InternalServerError,
StatusDescription = "Internal server error",
};
rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
}
}
}