private void HandleError(RewriteContext context)
        {
            // Return the status code.
            ContextFacade.SetStatusCode((int)context.StatusCode);

            // Get the error handler if there is one.
            IRewriteErrorHandler handler = _configuration.ErrorHandlers[(int)context.StatusCode] as IRewriteErrorHandler;

            if (handler != null)
            {
                try
                {
                    _configuration.Logger.Debug(MessageProvider.FormatString(Message.CallingErrorHandler));

                    // Execute the error handler.
                    ContextFacade.HandleError(handler);
                }
                catch (HttpException)
                {
                    throw;
                }
                catch (Exception exc)
                {
                    _configuration.Logger.Fatal(exc.Message, exc);
                    throw new HttpException(
                              (int)HttpStatusCode.InternalServerError, HttpStatusCode.InternalServerError.ToString());
                }
            }
            else
            {
                throw new HttpException((int)context.StatusCode, context.StatusCode.ToString());
            }
        }
Exemplo n.º 2
0
        private bool HandleDefaultDocument(RewriteContext context)
        {
            Uri        uri = new Uri(ContextFacade.GetRequestUrl(), context.Location);
            UriBuilder b   = new UriBuilder(uri);

            b.Path += "/";
            uri     = b.Uri;
            if (uri.Host == ContextFacade.GetRequestUrl().Host)
            {
                string filename = ContextFacade.MapPath(uri.AbsolutePath);
                if (Directory.Exists(filename))
                {
                    foreach (string document in RewriterConfiguration.Current.DefaultDocuments)
                    {
                        string pathName = Path.Combine(filename, document);
                        if (File.Exists(pathName))
                        {
                            context.Location = new Uri(uri, document).AbsolutePath;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
 private void AppendHeaders(RewriteContext context)
 {
     foreach (string headerKey in context.Headers)
     {
         ContextFacade.AppendHeader(headerKey, context.Headers[headerKey]);
     }
 }
 private void AppendCookies(RewriteContext context)
 {
     for (int i = 0; i < context.Cookies.Count; i++)
     {
         HttpCookie cookie = context.Cookies[i];
         ContextFacade.AppendCookie(cookie);
     }
 }
        /// <summary>
        /// Performs the rewriting.
        /// </summary>
        public void Rewrite()
        {
            string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");

            RawUrl = originalUrl;

            // Create the context
            RewriteContext context = new RewriteContext(this, originalUrl,
                                                        ContextFacade.GetHttpMethod(), ContextFacade.MapPath,
                                                        ContextFacade.GetServerVariables(), ContextFacade.GetHeaders(), ContextFacade.GetCookies());

            // Process each rule.
            ProcessRules(context);

            // Append any headers defined.
            AppendHeaders(context);

            // Append any cookies defined.
            AppendCookies(context);

            // Rewrite the path if the location has changed.
            ContextFacade.SetStatusCode((int)context.StatusCode);
            if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
            {
                if ((int)context.StatusCode < 300)
                {
                    // Successful status if less than 300
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RewritingXtoY,
                                                                            ContextFacade.GetRawUrl(), context.Location));

                    // Verify that the url exists on this server.
                    HandleDefaultDocument(context);// VerifyResultExists(context);

                    ContextFacade.RewritePath(context.Location);
                }
                else
                {
                    // Redirection
                    _configuration.Logger.Info(MessageProvider.FormatString(Message.RedirectingXtoY,
                                                                            ContextFacade.GetRawUrl(), context.Location));

                    ContextFacade.SetRedirectLocation(context.Location);
                }
            }
            else if ((int)context.StatusCode >= 400)
            {
                HandleError(context);
            }
            else if (HandleDefaultDocument(context))
            {
                ContextFacade.RewritePath(context.Location);
            }

            // Sets the context items.
            SetContextItems(context);
        }
Exemplo n.º 6
0
        private void SetContextItems(RewriteContext context)
        {
            OriginalQueryString = new Uri(ContextFacade.GetRequestUrl(), ContextFacade.GetRawUrl()).Query.Replace("?", "");
            QueryString         = new Uri(ContextFacade.GetRequestUrl(), context.Location).Query.Replace("?", "");

            // Add in the properties as context items, so these will be accessible to the handler
            foreach (string key in context.Properties.Keys)
            {
                ContextFacade.SetItem(String.Format("Rewriter.{0}", key), context.Properties[key]);
            }
        }
Exemplo n.º 7
0
        private static MapRepresentation CreateMap(ContextFacade context, object obj)
        {
            var opts = new List <OptionalProperty> {
                new OptionalProperty(JsonPropertyNames.Value, obj)
            };

            if (!string.IsNullOrEmpty(context.Reason))
            {
                opts.Add(new OptionalProperty(JsonPropertyNames.InvalidReason, context.Reason));
            }
            return(Create(opts.ToArray()));
        }
        private static void CheckForRedirection(IOidStrategy oidStrategy, ContextFacade context, HttpRequest req)
        {
            var ocs        = context as ObjectContextFacade;
            var arcs       = context as ActionResultContextFacade;
            var redirected = ocs?.Redirected ?? arcs?.Result?.Redirected;

            if (redirected != null)
            {
                var(serverName, oid) = redirected.Value;
                var redirectAddress = UriMtHelper.GetRedirectUri(req, serverName, oid);
                throw new RedirectionException(redirectAddress);
            }
        }
Exemplo n.º 9
0
        private static void CheckForRedirection(IOidStrategy oidStrategy, ContextFacade context, HttpRequestMessage req)
        {
            var    ocs  = context as ObjectContextFacade;
            var    arcs = context as ActionResultContextFacade;
            string url  = (ocs != null ? ocs.RedirectedUrl : null) ?? (arcs != null && arcs.Result != null ? arcs.Result.RedirectedUrl : null);

            if (url != null)
            {
                Uri redirectAddress = new UriMtHelper(oidStrategy, req).GetRedirectUri(req, url);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MovedPermanently)
                {
                    Headers = { Location = redirectAddress }
                });
            }
        }
        /// <summary>
        /// Resolves an Application-path relative location
        /// </summary>
        /// <param name="location">The location</param>
        /// <returns>The absolute location.</returns>
        public string ResolveLocation(string location)
        {
            if (location == null)
            {
                throw new ArgumentNullException("location");
            }

            string appPath = ContextFacade.GetApplicationPath();

            if (appPath.Length > 1)
            {
                appPath += "/";
            }

            return(location.Replace("~/", appPath));
        }
 private void VerifyResultExists(RewriteContext context)
 {
     if ((String.Compare(context.Location, ContextFacade.GetRawUrl()) != 0) && ((int)context.StatusCode < 300))
     {
         Uri uri = new Uri(ContextFacade.GetRequestUrl(), context.Location);
         if (uri.Host == ContextFacade.GetRequestUrl().Host)
         {
             string filename = ContextFacade.MapPath(uri.AbsolutePath);
             if (!File.Exists(filename))
             {
                 _configuration.Logger.Debug(MessageProvider.FormatString(Message.ResultNotFound, filename));
                 context.StatusCode = HttpStatusCode.NotFound;
             }
             else
             {
                 HandleDefaultDocument(context);
             }
         }
     }
 }
 private RestSnapshot(IOidStrategy oidStrategy, ContextFacade context, HttpRequestMessage req, bool validateAsJson)
     : this(oidStrategy, req, validateAsJson)
 {
     CheckForRedirection(oidStrategy, context, req);
 }
 public BadRequestNOSException(string message, ContextFacade context) : base(message, context)
 {
 }
        public static MapRepresentation Create(IOidStrategy oidStrategy, IFrameworkFacade frameworkFacade, HttpRequest req, ContextFacade contextFacade, IList <ContextFacade> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt)
        {
            var memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, frameworkFacade, req, c, flags))).ToList();
            var target       = contexts.First().Target;
            MapRepresentation mapRepresentation;

            if (format == Format.Full)
            {
                var tempProperties = new List <OptionalProperty>();

                if (!string.IsNullOrEmpty(contextFacade?.Reason))
                {
                    tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason));
                }

                var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName(oidStrategy));
                tempProperties.Add(dt);

                var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues.ToArray()));
                tempProperties.Add(members);
                mapRepresentation = Create(tempProperties.ToArray());
            }
            else
            {
                mapRepresentation = Create(memberValues.ToArray());
            }

            mapRepresentation.SetContentType(mt);

            return(mapRepresentation);
        }
        private static MapRepresentation GetMap(IOidStrategy oidStrategy, IFrameworkFacade frameworkFacade, HttpRequest req, ContextFacade context, RestControlFlags flags)
        {
            MapRepresentation value;

            // All reasons why we cannot create a link representation
            if (context.Specification.IsCollection && context.ElementSpecification != null && !context.ElementSpecification.IsParseable)
            {
                var proposedObjectFacade = frameworkFacade.GetObject(context.ProposedValue);
                var coll = proposedObjectFacade.ToEnumerable().Select(no => CreateObjectRef(oidStrategy, req, no, flags)).ToArray();
                value = CreateMap(context, coll);
            }
            else if (context.Specification.IsParseable ||
                     context.ProposedValue == null ||
                     context.ProposedObjectFacade == null ||
                     context.ProposedObjectFacade.Specification.IsParseable)
            {
                value = CreateMap(context, context.ProposedValue);
            }
            else
            {
                value = CreateMap(context, RefValueRepresentation.Create(oidStrategy, new ObjectRelType(RelValues.Self, new UriMtHelper(oidStrategy, req, context.ProposedObjectFacade)), flags));
            }

            return(value);
        }
        public static MapRepresentation Create(IOidStrategy oidStrategy, IFrameworkFacade frameworkFacade, HttpRequest req, ContextFacade context, Format format, RestControlFlags flags, MediaTypeHeaderValue mt)
        {
            var objectContext       = context as ObjectContextFacade;
            var actionResultContext = context as ActionResultContextFacade;
            MapRepresentation mapRepresentation;

            if (objectContext != null)
            {
                var optionalProperties = objectContext.VisibleProperties.Where(p => p.Reason != null || p.ProposedValue != null).Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, frameworkFacade, req, c, flags))).ToList();
                if (!string.IsNullOrEmpty(objectContext.Reason))
                {
                    optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, objectContext.Reason));
                }

                mapRepresentation = Create(optionalProperties.ToArray());
            }
            else if (actionResultContext != null)
            {
                var optionalProperties = actionResultContext.ActionContext.VisibleParameters.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, frameworkFacade, req, c, flags))).ToList();

                if (!string.IsNullOrEmpty(actionResultContext.Reason))
                {
                    optionalProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, actionResultContext.Reason));
                }

                mapRepresentation = Create(optionalProperties.ToArray());
            }
            else
            {
                mapRepresentation = GetMap(oidStrategy, frameworkFacade, req, context, flags);
            }

            mapRepresentation.SetContentType(mt);

            return(mapRepresentation);
        }
Exemplo n.º 17
0
 protected WithContextNOSException(string message, ContextFacade context) : this(message, context, null)
 {
 }
 public BadArgumentsNOSException(string message, ContextFacade context)
     : base(message, context)
 {
 }
        public static MapRepresentation Create(IOidStrategy oidStrategy, HttpRequestMessage req, ContextFacade contextFacade, IList <ContextFacade> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt)
        {
            var               memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, req, c, flags))).ToList();
            IObjectFacade     target       = contexts.First().Target;
            MapRepresentation mapRepresentation;

            if (format == Format.Full)
            {
                var tempProperties = new List <OptionalProperty>();

                if (contextFacade != null && !string.IsNullOrEmpty(contextFacade.Reason))
                {
                    tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason));
                }

                if (flags.SimpleDomainModel)
                {
                    var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName(oidStrategy));
                    tempProperties.Add(dt);
                }

                if (flags.FormalDomainModel)
                {
                    var links = new OptionalProperty(JsonPropertyNames.Links, new[] {
                        Create(new OptionalProperty(JsonPropertyNames.Rel, RelValues.DescribedBy),
                               new OptionalProperty(JsonPropertyNames.Href, new UriMtHelper(oidStrategy, req, target.Specification).GetDomainTypeUri()))
                    });
                    tempProperties.Add(links);
                }

                if (contextFacade != null && !string.IsNullOrEmpty(contextFacade.Reason))
                {
                    tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason));
                }


                var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues.ToArray()));
                tempProperties.Add(members);
                mapRepresentation = Create(tempProperties.ToArray());
            }
            else
            {
                mapRepresentation = Create(memberValues.ToArray());
            }

            mapRepresentation.SetContentType(mt);

            return(mapRepresentation);
        }
        private static MapRepresentation GetMap(IOidStrategy oidStrategy, HttpRequestMessage req, ContextFacade context, RestControlFlags flags)
        {
            MapRepresentation value;

            // All reasons why we cannot create a linkrep
            if (context.Specification.IsParseable ||
                context.Specification.IsCollection ||
                context.ProposedValue == null ||
                context.ProposedObjectFacade == null ||
                context.ProposedObjectFacade.Specification.IsParseable)
            {
                value = CreateMap(context, context.ProposedValue);
            }
            else
            {
                value = CreateMap(context, RefValueRepresentation.Create(oidStrategy, new ObjectRelType(RelValues.Self, new UriMtHelper(oidStrategy, req, context.ProposedObjectFacade)), flags));
            }
            return(value);
        }
Exemplo n.º 21
0
 private RestSnapshot(IOidStrategy oidStrategy, ContextFacade context, HttpRequestMessage req, bool validateAsJson)
     : this(oidStrategy, req, validateAsJson)
 {
     logger.DebugFormat("RestSnapshot:{0}", context.GetType().FullName);
     CheckForRedirection(oidStrategy, context, req);
 }
 public BadArgumentsNOSException(string message, ContextFacade context, IList <ContextFacade> contexts)
     : base(message, context, contexts)
 {
 }
Exemplo n.º 23
0
 protected WithContextNOSException(string message, ContextFacade context, IList <ContextFacade> contexts) : this(message) {
     Contexts      = contexts;
     ContextFacade = context;
 }
        /// <summary>
        /// Performs the rewriting.
        /// </summary>
        public void Rewrite()
        {
            string originalUrl = ContextFacade.GetRawUrl().Replace("+", " ");

            RawUrl = originalUrl;

            // Create the context
            RewriteContext context = new RewriteContext(
                this,
                originalUrl,
                ContextFacade.GetHttpMethod(),
                ContextFacade.MapPath,
                ContextFacade.GetServerVariables(),
                ContextFacade.GetHeaders(),
                ContextFacade.GetCookies());

            // Process each rule.
            ProcessRules(context);

            // Append any headers defined.
            AppendHeaders(context);

            // Append any cookies defined.
            AppendCookies(context);

            // Rewrite the path if the location has changed.
            ContextFacade.SetStatusCode((int)context.StatusCode);
            if ((context.Location != originalUrl) && ((int)context.StatusCode < 400))
            {
                if ((int)context.StatusCode < 300)
                {
                    // Successful status if less than 300
                    _configuration.Logger.Info(
                        MessageProvider.FormatString(Message.RewritingXtoY, ContextFacade.GetRawUrl(), context.Location));

                    // Verify that the url exists on this server.
                    HandleDefaultDocument(context); // VerifyResultExists(context);

                    if (context.Location.Contains(@"&"))
                    {
                        var queryStringCollection = HttpUtility.ParseQueryString(new Uri(this.ContextFacade.GetRequestUrl(), context.Location).Query);

                        StringBuilder builder = new StringBuilder();
                        foreach (var value in queryStringCollection.AllKeys.Distinct())
                        {
                            var argument = queryStringCollection.GetValues(value).FirstOrDefault();
                            if (value == "g")
                            {
                                if (context.Location != argument)
                                {
                                    builder.AppendFormat(
                                        "{0}={1}&",
                                        value,
                                        argument);
                                }
                            }
                            else
                            {
                                builder.AppendFormat(
                                    "{0}={1}&",
                                    value,
                                    argument);
                            }
                        }

                        context.Location = context.Location.Remove(context.Location.IndexOf("?") + 1);
                        context.Location = context.Location + builder;

                        if (context.Location.EndsWith(@"&"))
                        {
                            context.Location = context.Location.Remove(context.Location.Length - 1);
                        }
                    }

                    ContextFacade.RewritePath(context.Location);
                }
                else
                {
                    // Redirection
                    _configuration.Logger.Info(
                        MessageProvider.FormatString(
                            Message.RedirectingXtoY, ContextFacade.GetRawUrl(), context.Location));

                    ContextFacade.SetRedirectLocation(context.Location);
                }
            }
            else if ((int)context.StatusCode >= 400)
            {
                HandleError(context);
            }
            else if (HandleDefaultDocument(context))
            {
                ContextFacade.RewritePath(context.Location);
            }

            // Sets the context items.
            SetContextItems(context);
        }
Exemplo n.º 25
0
 protected WithContextNOSException(string message, ContextFacade context)
     : base(message)
 {
     ContextFacade = context;
 }