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);
        }
        public Message Get(Message message)
        {
            HttpRequestMessageProperty  requestMessageProperty  = (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name];
            HttpResponseMessageProperty responseMessageProperty = new HttpResponseMessageProperty();

            if ((requestMessageProperty != null) && IsServiceUnchanged(requestMessageProperty.Headers[JsonGlobals.IfModifiedSinceString]))
            {
                Message responseMessage = Message.CreateMessage(MessageVersion.None, string.Empty);
                responseMessageProperty.StatusCode = HttpStatusCode.NotModified;
                responseMessage.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty);
                return(responseMessage);
            }

            string  proxyContent = this.GetProxyContent(UriTemplate.RewriteUri(this.endpoint.Address.Uri, requestMessageProperty.Headers[HttpRequestHeader.Host]));
            Message response     = new WebScriptMetadataMessage(string.Empty, proxyContent);

            responseMessageProperty.Headers.Add(JsonGlobals.LastModifiedString, ServiceLastModifiedRfc1123String);
            responseMessageProperty.Headers.Add(JsonGlobals.ExpiresString, ServiceLastModifiedRfc1123String);
            if (AspNetEnvironment.Current.AspNetCompatibilityEnabled)
            {
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
            }
            else
            {
                responseMessageProperty.Headers.Add(JsonGlobals.CacheControlString, JsonGlobals.publicString);
            }
            response.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty);
            return(response);
        }
        Message GetHelpPage()
        {
            Uri    baseUri  = UriTemplate.RewriteUri(OperationContext.Current.Channel.LocalAddress.Uri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]);
            string helpPage = this.helpPageCache.Lookup(baseUri.Authority);

            if (String.IsNullOrEmpty(helpPage))
            {
                helpPage = HelpHtmlBuilder.CreateHelpPage(baseUri, operationInfoDictionary.Values).ToString();
                if (HttpContext.Current == null)
                {
                    this.helpPageCache.AddOrUpdate(baseUri.Authority, helpPage);
                }
            }
            return(WebOperationContext.Current.CreateTextResponse(helpPage, "text/html"));
        }
        bool ShouldRedirectToUriWithSlashAtTheEnd(UriTemplateTable methodSpecificTable, Message message, Uri to)
        {
            UriBuilder ub = new UriBuilder(to);

            if (ub.Path.EndsWith("/", StringComparison.Ordinal))
            {
                return(false);
            }

            ub.Path = ub.Path + "/";
            Uri originalPlusSlash = ub.Uri;

            bool result = false;

            if (methodSpecificTable != null && methodSpecificTable.MatchSingle(originalPlusSlash) != null)
            {
                // as an optimization, we check the table that matched the request's method
                // first, as it is more probable that a hit happens there
                result = true;
            }
            else
            {
                // back-compat:
                // we will redirect as long as there is any method
                // - not necessary the one the user is looking for -
                // that matches the uri with a slash at the end

                foreach (KeyValuePair <string, UriTemplateTable> pair in methodSpecificTables)
                {
                    UriTemplateTable table = pair.Value;
                    if (table != methodSpecificTable && table.MatchSingle(originalPlusSlash) != null)
                    {
                        result = true;
                        break;
                    }
                }
            }

            if (result)
            {
                string hostAndPort = GetAuthority(message);
                originalPlusSlash = UriTemplate.RewriteUri(ub.Uri, hostAndPort);
                message.Properties.Add(RedirectPropertyName, originalPlusSlash);
            }
            return(result);
        }
        Message GetOperationHelpPage(string operation)
        {
            Uri    requestUri = UriTemplate.RewriteUri(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]);
            string helpPage   = this.operationPageCache.Lookup(requestUri.AbsoluteUri);

            if (String.IsNullOrEmpty(helpPage))
            {
                OperationHelpInformation operationInfo;
                if (this.operationInfoDictionary.TryGetValue(operation, out operationInfo))
                {
                    Uri baseUri = UriTemplate.RewriteUri(OperationContext.Current.Channel.LocalAddress.Uri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]);
                    helpPage = HelpHtmlBuilder.CreateOperationHelpPage(baseUri, operationInfo).ToString();
                    if (HttpContext.Current == null)
                    {
                        this.operationPageCache.AddOrUpdate(requestUri.AbsoluteUri, helpPage);
                    }
                }
                else
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WebFaultException(HttpStatusCode.NotFound));
                }
            }
            return(WebOperationContext.Current.CreateTextResponse(helpPage, "text/html"));
        }
예제 #6
0
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            Message message = inputs[0] as Message;

            outputs = null;
#pragma warning disable 56506 // Microsoft, message.Properties is never null
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                              SR2.GetString(SR2.HttpUnhandledOperationInvokerCalledWithoutMessage)));
            }
            // We might be here because we desire a redirect...
            Uri newLocation = null;
            Uri to          = message.Headers.To;
            if (message.Properties.ContainsKey(WebHttpDispatchOperationSelector.RedirectPropertyName))
            {
                newLocation = message.Properties[WebHttpDispatchOperationSelector.RedirectPropertyName] as Uri;
            }
            if (newLocation != null && to != null)
            {
                // ...redirect
                Message redirectResult = WebOperationContext.Current.CreateStreamResponse(s => HelpHtmlBuilder.CreateTransferRedirectPage(to.AbsoluteUri, newLocation.AbsoluteUri).Save(s, SaveOptions.OmitDuplicateNamespaces), Atom10Constants.HtmlMediaType);
                WebOperationContext.Current.OutgoingResponse.Location    = newLocation.AbsoluteUri;
                WebOperationContext.Current.OutgoingResponse.StatusCode  = HttpStatusCode.TemporaryRedirect;
                WebOperationContext.Current.OutgoingResponse.ContentType = HtmlContentType;

                // Note that no exception is thrown along this path, even if the debugger is attached
                if (DiagnosticUtility.ShouldTraceInformation)
                {
                    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.WebRequestRedirect,
                                            SR2.GetString(SR2.TraceCodeWebRequestRedirect, to, newLocation));
                }
                return(redirectResult);
            }
            // otherwise we are here to issue either a 404 or a 405
            bool uriMatched = false;
            if (message.Properties.ContainsKey(WebHttpDispatchOperationSelector.HttpOperationSelectorUriMatchedPropertyName))
            {
                uriMatched = (bool)message.Properties[WebHttpDispatchOperationSelector.HttpOperationSelectorUriMatchedPropertyName];
            }
#pragma warning enable 56506
            Message result  = null;
            Uri     helpUri = this.HelpUri != null?UriTemplate.RewriteUri(this.HelpUri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]) : null;

            if (uriMatched)
            {
                WebHttpDispatchOperationSelectorData allowedMethodsData = null;
                if (message.Properties.TryGetValue(WebHttpDispatchOperationSelector.HttpOperationSelectorDataPropertyName, out allowedMethodsData))
                {
                    WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.Allow] = allowedMethodsData.AllowHeader;
                }
                result = WebOperationContext.Current.CreateStreamResponse(s => HelpHtmlBuilder.CreateMethodNotAllowedPage(helpUri).Save(s, SaveOptions.OmitDuplicateNamespaces), Atom10Constants.HtmlMediaType);
            }
            else
            {
                result = WebOperationContext.Current.CreateStreamResponse(s => HelpHtmlBuilder.CreateEndpointNotFound(helpUri).Save(s, SaveOptions.OmitDuplicateNamespaces), Atom10Constants.HtmlMediaType);
            }
            WebOperationContext.Current.OutgoingResponse.StatusCode  = uriMatched ? HttpStatusCode.MethodNotAllowed : HttpStatusCode.NotFound;
            WebOperationContext.Current.OutgoingResponse.ContentType = HtmlContentType;

            try
            {
                if (!uriMatched)
                {
                    if (Debugger.IsAttached)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchOperation,
                                                                                                                                OperationContext.Current.IncomingMessageHeaders.To)));
                    }
                    else
                    {
                        DiagnosticUtility.TraceHandledException(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchOperation,
                                                                                                            OperationContext.Current.IncomingMessageHeaders.To)), TraceEventType.Warning);
                    }
                }
                else
                {
                    if (Debugger.IsAttached)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchMethod,
                                                                                                                                WebOperationContext.Current.IncomingRequest.Method, OperationContext.Current.IncomingMessageHeaders.To)));
                    }
                    else
                    {
                        DiagnosticUtility.TraceHandledException(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchMethod,
                                                                                                            WebOperationContext.Current.IncomingRequest.Method, OperationContext.Current.IncomingMessageHeaders.To)), TraceEventType.Warning);
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // catch the exception - its only used for tracing
            }
            return(result);
        }