File: OutgoingWebResponseContext.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (320 lines) | stat: -rw-r--r-- 12,685 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
#pragma warning disable 1634, 1691

namespace System.ServiceModel.Web
{
    using System;
    using System.Globalization;
    using System.Net;
    using System.Runtime;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.Text;
    using System.Collections.Generic;

    public class OutgoingWebResponseContext
    {
        internal static readonly string WebResponseFormatPropertyName = "WebResponseFormatProperty";
        internal static readonly string AutomatedFormatSelectionContentTypePropertyName = "AutomatedFormatSelectionContentTypePropertyName";

        Encoding bindingWriteEncoding = null;

        OperationContext operationContext;
        internal OutgoingWebResponseContext(OperationContext operationContext)
        {
            Fx.Assert(operationContext != null, "operationContext is null");
            this.operationContext = operationContext;
        }

        public long ContentLength
        {
            get { return long.Parse(this.MessageProperty.Headers[HttpResponseHeader.ContentLength], CultureInfo.InvariantCulture); }
            set { this.MessageProperty.Headers[HttpResponseHeader.ContentLength] = value.ToString(CultureInfo.InvariantCulture); }
        }

        public string ContentType
        {
            get { return this.MessageProperty.Headers[HttpResponseHeader.ContentType]; }
            set { this.MessageProperty.Headers[HttpResponseHeader.ContentType] = value; }
        }

        public string ETag
        {
            get { return this.MessageProperty.Headers[HttpResponseHeader.ETag]; }
            set { this.MessageProperty.Headers[HttpResponseHeader.ETag] = value; }
        }

        public WebHeaderCollection Headers
        {
            get { return this.MessageProperty.Headers; }
        }

        public DateTime LastModified
        {
            get
            {
                string dateTime = this.MessageProperty.Headers[HttpRequestHeader.LastModified];
                if (!string.IsNullOrEmpty(dateTime))
                {
                    DateTime parsedDateTime;
                    if (DateTime.TryParse(dateTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime))
                    {
                        return parsedDateTime;
                    }
                }
                return DateTime.MinValue;
            }
            set
            {
                this.MessageProperty.Headers[HttpResponseHeader.LastModified] =
                    (value.Kind == DateTimeKind.Utc ?
                    value.ToString("R", CultureInfo.InvariantCulture) :
                    value.ToUniversalTime().ToString("R", CultureInfo.InvariantCulture));
            }
        }

        public string Location
        {
            get { return this.MessageProperty.Headers[HttpResponseHeader.Location]; }
            set { this.MessageProperty.Headers[HttpResponseHeader.Location] = value; }
        }

        public HttpStatusCode StatusCode
        {
            get { return this.MessageProperty.StatusCode; }
            set { this.MessageProperty.StatusCode = value; }
        }

        public string StatusDescription
        {
            get { return this.MessageProperty.StatusDescription; }
            set { this.MessageProperty.StatusDescription = value; }
        }

        public bool SuppressEntityBody
        {
            get { return this.MessageProperty.SuppressEntityBody; }
            set { this.MessageProperty.SuppressEntityBody = value; }
        }

        public WebMessageFormat? Format
        {
            get
            {
                if (!operationContext.OutgoingMessageProperties.ContainsKey(WebResponseFormatPropertyName))
                {
                    return null;
                }
                return operationContext.OutgoingMessageProperties[WebResponseFormatPropertyName] as WebMessageFormat?;
            }
            set
            {
                if (value.HasValue)
                {
                    if (!WebMessageFormatHelper.IsDefined(value.Value))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
                    }
                    else
                    {
                        operationContext.OutgoingMessageProperties[WebResponseFormatPropertyName] = value.Value;
                    }
                }
                else
                {
                    operationContext.OutgoingMessageProperties[WebResponseFormatPropertyName] = null;
                }
                this.AutomatedFormatSelectionContentType = null;
            }
        }

        // This is an internal property because we need to carry the content-type that was selected by the FormatSelectingMessageInspector
        // forward so that the formatter has access to it. However, we dond't want to use the ContentType property on this, because then
        // developers would have to clear the ContentType property manually when overriding the format set by the 
        // FormatSelectingMessageInspector
        internal string AutomatedFormatSelectionContentType
        {
            get
            {
                if (!operationContext.OutgoingMessageProperties.ContainsKey(AutomatedFormatSelectionContentTypePropertyName))
                {
                    return null;
                }
                return operationContext.OutgoingMessageProperties[AutomatedFormatSelectionContentTypePropertyName] as string;
            }
            set
            {
                operationContext.OutgoingMessageProperties[AutomatedFormatSelectionContentTypePropertyName] = value;
            }
        }

        public Encoding BindingWriteEncoding
        {
            get
            {
                if (this.bindingWriteEncoding == null)
                {
                    string endpointId = this.operationContext.EndpointDispatcher.Id;
                    Fx.Assert(endpointId != null, "There should always be an valid EndpointDispatcher.Id");
                    foreach (ServiceEndpoint endpoint in this.operationContext.Host.Description.Endpoints)
                    {
                        if (endpoint.Id == endpointId)
                        {
                            WebMessageEncodingBindingElement encodingElement = endpoint.Binding.CreateBindingElements().Find<WebMessageEncodingBindingElement>() as WebMessageEncodingBindingElement;
                            if (encodingElement != null)
                            {
                                this.bindingWriteEncoding = encodingElement.WriteEncoding;
                            }
                        }
                    }
                }
                return this.bindingWriteEncoding;
            }
        }

        internal HttpResponseMessageProperty MessageProperty
        {
            get
            {
                if (!operationContext.OutgoingMessageProperties.ContainsKey(HttpResponseMessageProperty.Name))
                {
                    operationContext.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, new HttpResponseMessageProperty());
                }
                return operationContext.OutgoingMessageProperties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
            }
        }

        public void SetETag(string entityTag)
        {
            this.ETag = GenerateValidEtagFromString(entityTag);
        }

        public void SetETag(int entityTag)
        {
            this.ETag = GenerateValidEtag(entityTag);
        }

        public void SetETag(long entityTag)
        {
            this.ETag = GenerateValidEtag(entityTag);
        }

        public void SetETag(Guid entityTag)
        {
            this.ETag = GenerateValidEtag(entityTag);
        }

        public void SetStatusAsCreated(Uri locationUri)
        {
            if (locationUri == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("locationUri");
            }
            this.StatusCode = HttpStatusCode.Created;
            this.Location = locationUri.ToString();
        }

        public void SetStatusAsNotFound()
        {
            this.StatusCode = HttpStatusCode.NotFound;
        }

        public void SetStatusAsNotFound(string description)
        {
            this.StatusCode = HttpStatusCode.NotFound;
            this.StatusDescription = description;
        }

        internal static string GenerateValidEtagFromString(string entityTag)
        {
            // This method will generate a valid entityTag from a string by doing the following:
            //   1) Adding surrounding double quotes if the string doesn't already start and end with them
            //   2) Escaping any internal double quotes that aren't already escaped (preceded with a backslash)
            //   3) If a string starts with a double quote but doesn't end with one, or vice-versa, then the 
            //      double quote is considered internal and is escaped.

            if (string.IsNullOrEmpty(entityTag))
            {
                return null;
            }

            if (entityTag.StartsWith("W/\"", StringComparison.OrdinalIgnoreCase) &&
                entityTag.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                    SR2.GetString(SR2.WeakEntityTagsNotSupported, entityTag)));
            }

            List<int> escapeCharacterInsertIndices = null;
            int lastEtagIndex = entityTag.Length - 1;
            bool startsWithQuote = entityTag[0] == '\"';
            bool endsWithQuote = entityTag[lastEtagIndex] == '\"';

            // special case where the entityTag is a single character, a double quote, '"'
            if (lastEtagIndex == 0 && startsWithQuote)
            {
                endsWithQuote = false;
            }

            bool needsSurroundingQuotes = !startsWithQuote || !endsWithQuote;

            if (startsWithQuote && !endsWithQuote)
            {
                if (escapeCharacterInsertIndices == null)
                {
                    escapeCharacterInsertIndices = new List<int>();
                }
                escapeCharacterInsertIndices.Add(0);
            }

            for (int x = 1; x < lastEtagIndex; x++)
            {
                if (entityTag[x] == '\"' && entityTag[x - 1] != '\\')
                {
                    if (escapeCharacterInsertIndices == null)
                    {
                        escapeCharacterInsertIndices = new List<int>();
                    }
                    escapeCharacterInsertIndices.Add(x + escapeCharacterInsertIndices.Count);
                }
            }

            // Possible that the ending internal quote is already escaped so must check the character before it
            if (!startsWithQuote && endsWithQuote && entityTag[lastEtagIndex - 1] != '\\')
            {
                if (escapeCharacterInsertIndices == null)
                {
                    escapeCharacterInsertIndices = new List<int>();
                }
                escapeCharacterInsertIndices.Add(lastEtagIndex + escapeCharacterInsertIndices.Count);
            }

            if (needsSurroundingQuotes || escapeCharacterInsertIndices != null)
            {
                int escapeCharacterInsertIndicesCount = (escapeCharacterInsertIndices == null) ? 0 : escapeCharacterInsertIndices.Count;
                StringBuilder editedEtag = new StringBuilder(entityTag, entityTag.Length + escapeCharacterInsertIndicesCount + 2);
                for (int x = 0; x < escapeCharacterInsertIndicesCount; x++)
                {
                    editedEtag.Insert(escapeCharacterInsertIndices[x], '\\');
                }
                if (needsSurroundingQuotes)
                {
                    editedEtag.Insert(entityTag.Length + escapeCharacterInsertIndicesCount, '\"');
                    editedEtag.Insert(0, '\"');
                }
                entityTag = editedEtag.ToString();
            }

            return entityTag;
        }

        internal static string GenerateValidEtag(object entityTag)
        {
            return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", entityTag.ToString());
        }
    }
}