File: WebErrorHandler.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (176 lines) | stat: -rw-r--r-- 8,798 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
#pragma warning disable 1634, 1691
namespace System.ServiceModel.Dispatcher
{
    using System;
    using System.Diagnostics;
    using System.Net;
    using System.Runtime;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Syndication;
    using System.ServiceModel.Web;
    using System.Xml.Linq;
    using System.Xml.Serialization;

    class WebErrorHandler : IErrorHandler
    {
        WebHttpBehavior webHttpBehavior;
        ContractDescription contractDescription;
        bool includeExceptionDetailInFaults;

        public WebErrorHandler(WebHttpBehavior webHttpBehavior, ContractDescription contractDescription, bool includeExceptionDetailInFaults)
        {
            this.webHttpBehavior = webHttpBehavior;
            this.contractDescription = contractDescription;
            this.includeExceptionDetailInFaults = includeExceptionDetailInFaults;
        }

        public bool HandleError(Exception error)
        {
            return false;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            if (version != MessageVersion.None || error == null)
            {
                return;
            }

            // If the exception is not derived from FaultException and the fault message is already present
            //   then only another error handler could have provided the fault so we should not replace it
            FaultException errorAsFaultException = error as FaultException;
            if (errorAsFaultException == null && fault != null)
            {
                return;
            }

            try
            {
                if (error is IWebFaultException)
                {
                    IWebFaultException webFaultException = (IWebFaultException)error;
                    WebOperationContext context = WebOperationContext.Current;
                    context.OutgoingResponse.StatusCode = webFaultException.StatusCode;
                    string operationName;
                    if (OperationContext.Current.IncomingMessageProperties.TryGetValue<string>(WebHttpDispatchOperationSelector.HttpOperationNamePropertyName, out operationName))
                    {
                        OperationDescription description = this.contractDescription.Operations.Find(operationName);
                        bool isXmlSerializerFaultFormat = WebHttpBehavior.IsXmlSerializerFaultFormat(description);
                        if (isXmlSerializerFaultFormat && WebOperationContext.Current.OutgoingResponse.Format == WebMessageFormat.Json)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.JsonFormatRequiresDataContract, description.Name, description.DeclaringContract.Name, description.DeclaringContract.Namespace)));
                        }
                        WebMessageFormat? nullableFormat = !isXmlSerializerFaultFormat ? context.OutgoingResponse.Format : WebMessageFormat.Xml;
                        WebMessageFormat format = nullableFormat.HasValue ? nullableFormat.Value : this.webHttpBehavior.GetResponseFormat(description);
                        if (webFaultException.DetailObject != null)
                        {
                            switch (format)
                            {
                                case WebMessageFormat.Json:
                                    fault = context.CreateJsonResponse(webFaultException.DetailObject, new DataContractJsonSerializer(webFaultException.DetailType, webFaultException.KnownTypes));
                                    break;
                                case WebMessageFormat.Xml:
                                    if (isXmlSerializerFaultFormat)
                                    {
                                        fault = context.CreateXmlResponse(webFaultException.DetailObject, new XmlSerializer(webFaultException.DetailType, webFaultException.KnownTypes));
                                    }
                                    else
                                    {
                                        fault = context.CreateXmlResponse(webFaultException.DetailObject, new DataContractSerializer(webFaultException.DetailType, webFaultException.KnownTypes));
                                    }
                                    break;
                            }
                        }
                        else
                        {
                            HttpResponseMessageProperty property;
                            if (OperationContext.Current.OutgoingMessageProperties.TryGetValue<HttpResponseMessageProperty>(HttpResponseMessageProperty.Name, out property) &&
                                property != null)
                            {
                                property.SuppressEntityBody = true;
                            }
                            if (format == WebMessageFormat.Json)
                            {
                                fault.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.JsonProperty);
                            }
                        }
                    }
                    else
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.OperationNameNotFound));
                    }
                }
                else
                {
                    fault = CreateHtmlResponse(error);
                }

            }
            catch (Exception ex)
            {
                if (Fx.IsFatal(ex))
                {
                    throw;
                }
                if (System.ServiceModel.DiagnosticUtility.ShouldTraceWarning)
                {
                    System.ServiceModel.DiagnosticUtility.TraceHandledException(new InvalidOperationException(SR2.GetString(SR2.HelpPageFailedToCreateErrorMessage)), TraceEventType.Warning);
                }

                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                fault = CreateHtmlResponse(ex);
            }
        }

        Message CreateHtmlResponse(Exception error)
        {
            // Note: WebOperationContext may not be present in case of an invalid HTTP request
            Uri helpUri = null;
            if (WebOperationContext.Current != null)
            {
                helpUri = this.webHttpBehavior.HelpUri != null ? UriTemplate.RewriteUri(this.webHttpBehavior.HelpUri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]) : null;
            }
            StreamBodyWriter bodyWriter;
            if (this.includeExceptionDetailInFaults)
            {
                bodyWriter = StreamBodyWriter.CreateStreamBodyWriter(s => HelpHtmlBuilder.CreateServerErrorPage(helpUri, error).Save(s, SaveOptions.OmitDuplicateNamespaces));
            }
            else
            {
                bodyWriter = StreamBodyWriter.CreateStreamBodyWriter(s => HelpHtmlBuilder.CreateServerErrorPage(helpUri, null).Save(s, SaveOptions.OmitDuplicateNamespaces));
            }
            Message response = new HttpStreamMessage(bodyWriter);
            response.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);

            HttpResponseMessageProperty responseProperty = GetResponseProperty(WebOperationContext.Current, response);
            if (!responseProperty.HasStatusCodeBeenSet)
            {
                responseProperty.StatusCode = HttpStatusCode.BadRequest;
            }
            responseProperty.Headers[HttpResponseHeader.ContentType] = Atom10Constants.HtmlMediaType;
            return response;
        }

        static HttpResponseMessageProperty GetResponseProperty(WebOperationContext currentContext, Message response)
        {
            HttpResponseMessageProperty responseProperty; 
            if (currentContext != null)
            {
                responseProperty = currentContext.OutgoingResponse.MessageProperty;
            }
            else
            {
                responseProperty = new HttpResponseMessageProperty();
                response.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
            }
            return responseProperty;
        }
    }
}