public virtual string BuildCacheKeyForMethodCall(IApiMethodCall apiMethodCall, IEnumerable<object> callArgs, ApiContext context)
 {
     return string.Format("{0}.{1}({2}),{3}:{4}",
                          apiMethodCall.MethodCall.DeclaringType.FullName,
                          apiMethodCall.MethodCall.Name,
                          string.Join(",", callArgs.Select(x => x.GetHashCode().ToString()).ToArray()),
                          apiMethodCall.MethodCall.DeclaringType.Assembly.FullName,context);
 }
Пример #2
0
 public Route GetRoute(IApiRouteHandler routeHandler, IApiMethodCall method, string extension)
 {
     var dataTokens = new RouteValueDictionary
                          {
                              {DataTokenConstants.RequiresAuthorization,method.RequiresAuthorization}
                          };
     return new Route(method.FullPath + extension, null, method.Constraints, dataTokens, routeHandler);
 }
        public override object InvokeMethod(IApiMethodCall methodToCall, object instance, IEnumerable<object> callArg, ApiContext apicontext)
        {
            string cacheKey = null;
            object result = null;
            IEnumerable<Type> knownTypes = null;
            

            var cacheManager = Container.Resolve<ICacheManager>();
            if (ShouldCacheMethod(methodToCall) && cacheManager != null)
            {
                cacheKey = BuildCacheKey(methodToCall, callArg, apicontext);
                result = cacheManager[cacheKey];
                knownTypes = cacheManager[cacheKey + "_knowntypes"] as IEnumerable<Type>;
                apicontext.FromCache = result != null;
                Log.Debug(apicontext.FromCache ? "hit from cache: {0}" : "miss from cache: {0}",
                          methodToCall);
            }
            if (result == null) //if not null than it's from cache
            {
                //Call api method
                var sw = new Stopwatch();
                sw.Start();
                result = base.InvokeMethod(methodToCall, instance, callArg, apicontext);
                sw.Stop();
                long cacheTime;
                bool shouldCache;
                GetCachingPolicy(methodToCall, sw.Elapsed, out cacheTime, out shouldCache);
                Log.Debug("cache policy: {0}",
                          cacheTime > 0 ? TimeSpan.FromMilliseconds(cacheTime).ToString() : "no-cache");
                knownTypes = apicontext.GetKnownTypes().ToList();

                if (cacheKey != null && cacheTime>0)
                {
                    cacheManager.Add(cacheKey,
                                     result,
                                     CacheItemPriority.Normal,
                                     null,
                                     new SlidingTime(TimeSpan.FromMilliseconds(cacheTime)));
                    if (knownTypes!=null)
                    {
                        cacheManager.Add(cacheKey + "_knowntypes",
                                     knownTypes,
                                     CacheItemPriority.Normal,
                                     null,
                                     new SlidingTime(TimeSpan.FromMilliseconds(cacheTime * 2)));
                    }
                    Log.Debug("added to cache: {0}. Key: {1}", methodToCall, cacheKey);

                }
            }
            //Get cached known types
            if (knownTypes!=null)
            {
                apicontext.RegisterTypes(knownTypes);
            }
            return result;
        }
 public Route GetPollRoute(IApiRouteHandler routeHandler, IApiMethodCall method, string extension)
 {
     Log.Debug("Long poll route:" + method.RoutingPollUrl + extension + " authorization:" + method.RequiresAuthorization);
     var dataTokens = new RouteValueDictionary
                          {
                              {DataTokenConstants.RequiresAuthorization,method.RequiresAuthorization},
                          };
     return new Route(method.RoutingPollUrl + extension, null, method.Constraints, dataTokens, routeHandler);
 }
 public override void PostMethodCall(IApiMethodCall method, ApiContext context, object methodResponce)
 {
     try
     {
         context.RequestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
     }
     catch (Exception err)
     {
         log.Warn(err.ToString());
     }
 }
 protected override void GetCachingPolicy(IApiMethodCall methodToCall, TimeSpan elapsed, out long cacheTime, out bool shouldCache)
 {
     if (elapsed.TotalMilliseconds>_maxuncahetime)
     {
         cacheTime = _cachetime;
         shouldCache = IsGetRequest(methodToCall);
     }
     else
     {
         base.GetCachingPolicy(methodToCall, elapsed, out cacheTime, out shouldCache);
     }
 }
        public override void PreMethodCall(IApiMethodCall method, ApiContext context, IEnumerable<object> arguments)
        {
            var header = context.RequestContext.HttpContext.Request.Headers["Payment-Info"];
            var flag = true;
            if (string.IsNullOrEmpty(header) || (bool.TryParse(header, out flag) && flag))
            {
                var tenant = CoreContext.TenantManager.GetCurrentTenant(false);
                if (tenant == null)
                {
                    var hostname = string.Empty;
                    try
                    {
                        hostname = HttpContext.Current.Request.GetUrlRewriter().Host;
                    }
                    catch { }
                    throw new System.Security.SecurityException(string.Format("Portal {0} not found.", hostname));
                }

                var tenantStatus = tenant.Status;
                if (tenantStatus == TenantStatus.Transfering)
                {
                    context.RequestContext.HttpContext.Response.StatusCode = 503;
                    context.RequestContext.HttpContext.Response.StatusDescription = "Service Unavailable";
                    log.Warn("Portal {0} is transfering to another region", context.RequestContext.HttpContext.Request.Url);
                }

                var tariff = CoreContext.PaymentManager.GetTariff(tenant.TenantId);
                if (tenantStatus != TenantStatus.Active || tariff.State == TariffState.NotPaid)
                {
                    context.RequestContext.HttpContext.Response.StatusCode = 402;
                    context.RequestContext.HttpContext.Response.StatusDescription = "Payment Required.";
                    log.Warn("Payment Required {0}.", context.RequestContext.HttpContext.Request.Url);
                }
            }

            if (!SecurityContext.IsAuthenticated) return;

            var pid = FindProduct(method);
            if (pid != Guid.Empty)
            {
                if (CallContext.GetData("asc.web.product_id") == null)
                {
                    CallContext.SetData("asc.web.product_id", pid);
                }
                if (!WebItemSecurity.IsAvailableForUser(pid.ToString(), SecurityContext.CurrentAccount.ID))
                {
                    context.RequestContext.HttpContext.Response.StatusCode = 403;
                    context.RequestContext.HttpContext.Response.StatusDescription = "Access denied.";
                    log.Warn("Product {0} denied for user {1}", method.Name, SecurityContext.CurrentAccount);
                }
            }
        }
Пример #8
0
        public override void PostMethodCall(IApiMethodCall method, ASC.Api.Impl.ApiContext context, object methodResponce)
        {
            var pubSub = ServiceLocator.Current.GetInstance<IApiPubSub>();

            if (pubSub != null)
            {
                pubSub.PublishDataForKey(
                    method.RoutingPollUrl + ":" +
                    PubSubKeyHelper.GetKeyForRoute(context.RequestContext.RouteData.Route.GetRouteData(context.RequestContext.HttpContext)),
                    new ApiMethodCallData(){Method = method,Result = methodResponce});
            }
            base.PostMethodCall(method, context, methodResponce);
        }
Пример #9
0
        protected void RespondTo(IApiMethodCall method, HttpContextBase context)
        {
            try
            {
                context.Response.Cache.SetETag(Guid.NewGuid().ToString("N"));
                context.Response.Cache.SetMaxAge(TimeSpan.FromSeconds(0));
            }
            catch (Exception)
            {
                //Nothing happens if we didn't set cache tags   
            }

            IApiResponder responder = null;

            if (method != null && method.Responders != null && method.Responders.Any())
            {
                try
                {
                    //Try custom responders
                    var methodCustomResponders = new List<IApiResponder>(method.Responders);
                    responder = methodCustomResponders.FirstOrDefault(x => x != null && x.CanRespondTo(ApiResponce, context));
                }
                catch (Exception)
                {
                    Log.Warn("Custom reponder for {0} failed", method.ToString());
                }
            }
            if (responder == null)
            {
                responder = Container.ResolveAll<IApiResponder>().FirstOrDefault(x => x.CanRespondTo(ApiResponce, context));
            }

            if (responder != null)
            {
                try
                {
                    responder.RespondTo(ApiResponce, context);
                }
                catch (Exception e)
                {
                    Log.Error(e, "Error while responding!");
                    throw;
                }
            }
            else
            {
                Log.Error(null, "no formatter error");
                throw new HttpException((int)HttpStatusCode.BadRequest, "No formatter");
            }
        }
Пример #10
0
        public object InvokeMethod(IApiMethodCall methodToCall, ApiContext apicontext)
        {
            if (apicontext == null) throw new ArgumentNullException("apicontext");

            if (methodToCall != null)
            {
                var context = apicontext.RequestContext;

                Log.Debug("Method to call={0}", methodToCall);
                object instance = _container.Resolve(methodToCall.ApiClassType, new DependencyOverride(typeof(ApiContext), apicontext));

                //try convert params
                var callArg = ArgumentBuilder.BuildCallingArguments(context, methodToCall);
                if (_paramInspectors.Any())
                {
                    callArg = _paramInspectors.Aggregate(callArg,
                                                   (current, apiParamInspector) =>
                                                   apiParamInspector.InspectParams(current));
                }

                Log.Debug("Arguments count: {0}", callArg == null ? "empty" : callArg.Count().ToString());


                try
                {
                    //Pre call filter
                    methodToCall.Filters.ForEach(x => x.PreMethodCall(methodToCall, apicontext, callArg));
                    if (apicontext.RequestContext.HttpContext.Response.StatusCode != 200)
                    {
                        return new HttpException(apicontext.RequestContext.HttpContext.Response.StatusCode, apicontext.RequestContext.HttpContext.Response.StatusDescription);
                    }

                    object result = _invoker.InvokeMethod(methodToCall, instance, callArg, apicontext);
                    //Post call filter
                    methodToCall.Filters.ForEach(x => x.PostMethodCall(methodToCall, apicontext, result));
                    return result;
                }
                catch (Exception e)
                {
                    methodToCall.Filters.ForEach(x => x.ErrorMethodCall(methodToCall, apicontext, e));
                    throw;
                }
            }
            throw new ApiBadHttpMethodException();
        }
Пример #11
0
        public override void PreMethodCall(IApiMethodCall method, ApiContext context, IEnumerable<object> arguments)
        {
            if (!SecurityContext.IsAuthenticated) return;

            var pid = FindProduct(method.Name);
            if (pid != Guid.Empty)
            {
                if (CallContext.GetData("asc.web.product_id") == null)
                {
                    CallContext.SetData("asc.web.product_id", pid);
                }
                if (!WebItemSecurity.IsAvailableForUser(pid.ToString(), SecurityContext.CurrentAccount.ID))
                {
                    context.RequestContext.HttpContext.Response.StatusCode = 403;
                    context.RequestContext.HttpContext.Response.StatusDescription = "Access denied.";
                    context.RequestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    throw new System.Security.SecurityException(string.Format("Product {0} denied for user {1}", method.Name, SecurityContext.CurrentAccount));
                }
            }
        }
 private void TryLog(LogEntry.Actions action, IApiMethodCall method, ApiContext context, Exception exception)
 {
     try
     {
         ThreadContext.Properties["HostAddress"] = context.RequestContext.HttpContext.Request.UserHostAddress;
         ThreadContext.Properties["Referer"] = context.RequestContext.HttpContext.Request.UrlReferrer;
         ThreadContext.Properties["HttpMethod"] = method.HttpMethod;
         ThreadContext.Properties["ApiRoute"] = method.FullPath;
         ThreadContext.Properties["Url"] = context.RequestContext.HttpContext.Request.GetUrlRewriter();
         ThreadContext.Properties["TenantId"] = CoreContext.TenantManager.GetCurrentTenant(false).TenantId;
         ThreadContext.Properties["UserId"] = SecurityContext.CurrentAccount.ID;
         ThreadContext.Properties["ExecutionTime"] = Sw.ElapsedMilliseconds;
         ThreadContext.Properties["Error"] = exception;
         ThreadContext.Properties["Action"] = action;
         _loger.Debug("log");
     }
     catch
     {
     }
 }
Пример #13
0
 public virtual void PostMethodCall(IApiMethodCall method, ApiContext context, object methodResponce)
 {
 }
 public override void PostMethodCall(IApiMethodCall method, ASC.Api.Impl.ApiContext context, object methodResponce)
 {
     Sw.Stop();
     TryLog(LogEntry.Actions.AfterCall, method, context, null);
     base.PostMethodCall(method, context, methodResponce);
 }
 protected virtual void GetCachingPolicy(IApiMethodCall methodToCall, TimeSpan elapsed, out long cacheTime, out bool shouldCache)
 {
     cacheTime = methodToCall.CacheTime;
     shouldCache = ShouldCacheMethod(methodToCall);
 }
 protected virtual bool ShouldCacheMethod(IApiMethodCall methodToCall)
 {
     return "get".Equals(methodToCall.HttpMethod, StringComparison.OrdinalIgnoreCase) && methodToCall.ShouldCache;
 }
Пример #17
0
 protected override bool ShouldCacheMethod(IApiMethodCall methodToCall)
 {
     return(IsGetRequest(methodToCall));
 }
        public IEnumerable <object> BuildCallingArguments(RequestContext context, IApiMethodCall methodToCall)
        {
            var callArg       = new List <object>();
            var requestParams = GetRequestParams(context);

            var methodParams = methodToCall.GetParams().Where(x => !x.IsRetval).OrderBy(x => x.Position);


            foreach (var parameterInfo in methodParams)
            {
                if (requestParams[parameterInfo.Name] != null)
                {
                    //convert
                    var values = requestParams.GetValues(parameterInfo.Name);
                    if (values != null && values.Any())
                    {
                        if (Binder.IsCollection(parameterInfo.ParameterType))
                        {
                            callArg.Add(Binder.Bind(parameterInfo.ParameterType, requestParams, parameterInfo.Name));
                            continue; //Go to next loop
                        }

                        try
                        {
                            callArg.Add(ConvertUtils.GetConverted(values.First(), parameterInfo)); //NOTE; Get first value!
                        }
                        catch (ApiArgumentMismatchException)
                        {
                            //Failed to convert. Try bind
                            callArg.Add(Binder.Bind(parameterInfo.ParameterType, requestParams, parameterInfo.Name));
                        }
                    }
                }
                else
                {
                    //try get request param first. It may be form\url-encoded
                    if (!"GET".Equals(context.HttpContext.Request.HttpMethod, StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(context.HttpContext.Request[parameterInfo.Name]))
                    {
                        //Drop to
                        callArg.Add(ConvertUtils.GetConverted(context.HttpContext.Request[parameterInfo.Name], parameterInfo));
                    }
                    else if (parameterInfo.ParameterType == typeof(ContentType) && !string.IsNullOrEmpty(context.HttpContext.Request.ContentType))
                    {
                        callArg.Add(new ContentType(context.HttpContext.Request.ContentType));
                    }
                    else if (parameterInfo.ParameterType == typeof(ContentDisposition) && !string.IsNullOrEmpty(context.HttpContext.Request.Headers["Content-Disposition"]))
                    {
                        var disposition = new ContentDisposition(context.HttpContext.Request.Headers["Content-Disposition"]);
                        disposition.FileName = HttpUtility.UrlDecode(disposition.FileName); //Decode uri name
                        callArg.Add(disposition);
                    }
                    else if (parameterInfo.ParameterType.IsSubclassOf(typeof(HttpPostedFile)) && context.HttpContext.Request.Files[parameterInfo.Name] != null)
                    {
                        callArg.Add(context.HttpContext.Request.Files[parameterInfo.Name]);
                    }
                    else if (Binder.IsCollection(parameterInfo.ParameterType) && parameterInfo.ParameterType.IsGenericType && parameterInfo.ParameterType.GetGenericArguments().First() == typeof(HttpPostedFileBase))
                    {
                        //File catcher
                        var files = new List <HttpPostedFileBase>(context.HttpContext.Request.Files.Count);
                        files.AddRange(from string key in context.HttpContext.Request.Files select context.HttpContext.Request.Files[key]);
                        callArg.Add(files);
                    }
                    else
                    {
                        if (parameterInfo.ParameterType.IsSubclassOf(typeof(Stream)) || parameterInfo.ParameterType == typeof(Stream))
                        {
                            //First try get files
                            var file = context.HttpContext.Request.Files[parameterInfo.Name];
                            callArg.Add(file != null ? file.InputStream : context.HttpContext.Request.InputStream);
                        }
                        else
                        {
                            //Try bind
                            //Note: binding moved here
                            if (IsTypeBindable(parameterInfo.ParameterType))
                            {
                                //Custom type
                                var binded = Binder.Bind(parameterInfo.ParameterType,
                                                         requestParams,
                                                         parameterInfo.Name);

                                if (binded != null)
                                {
                                    callArg.Add(binded);
                                    continue; //Go to next loop
                                }
                            }
                            //Create null
                            var obj = parameterInfo.ParameterType.IsValueType ? Activator.CreateInstance(parameterInfo.ParameterType) : null;
                            callArg.Add(obj);
                        }
                    }
                }
            }
            return(callArg);
        }
Пример #19
0
 public virtual void PreMethodCall(IApiMethodCall method, ApiContext context, IEnumerable <object> arguments)
 {
 }
Пример #20
0
 private string GetFullPollPath(string apiBasePathPath, IApiMethodCall apiMethodCall)
 {
     return GetFullPath(apiBasePathPath, apiMethodCall) + Config.ApiSeparator + apiMethodCall.RoutingPollUrl.TrimStart(Config.ApiSeparator).TrimEnd('/');
 }
Пример #21
0
 public bool Equals(IApiMethodCall other)
 {
     return(Equals(other as ApiMethodCall));
 }
Пример #22
0
 private string GetFullPath(string apiBasePathPath, IApiMethodCall apiMethodCall)
 {
     return (apiBasePathPath + apiMethodCall.Name + Config.ApiSeparator +
             apiMethodCall.RoutingUrl.TrimStart(Config.ApiSeparator)).TrimEnd('/');
 }
        public override void PreMethodCall(IApiMethodCall method, ApiContext context, IEnumerable <object> arguments)
        {
            if (context.RequestContext.RouteData.DataTokens.ContainsKey(DataTokenConstants.CheckPayment) &&
                !(bool)context.RequestContext.RouteData.DataTokens[DataTokenConstants.CheckPayment])
            {
                log.Debug("Payment is not required");
            }
            else
            {
                var  header = context.RequestContext.HttpContext.Request.Headers["Payment-Info"];
                bool flag;
                if (string.IsNullOrEmpty(header) || (bool.TryParse(header, out flag) && flag))
                {
                    var tenant = CoreContext.TenantManager.GetCurrentTenant(false);
                    if (tenant == null)
                    {
                        var hostname = string.Empty;
                        try
                        {
                            hostname = HttpContext.Current.Request.GetUrlRewriter().Host;
                        }
                        catch
                        {
                        }
                        throw new System.Security.SecurityException(string.Format("Portal {0} not found.", hostname));
                    }

                    var tenantStatus = tenant.Status;
                    if (tenantStatus == TenantStatus.Transfering)
                    {
                        context.RequestContext.HttpContext.Response.StatusCode        = (int)HttpStatusCode.ServiceUnavailable;
                        context.RequestContext.HttpContext.Response.StatusDescription = HttpStatusCode.ServiceUnavailable.ToString();
                        log.Warn("Portal {0} is transfering to another region", context.RequestContext.HttpContext.Request.Url);
                    }

                    var tariff = CoreContext.PaymentManager.GetTariff(tenant.TenantId);
                    if (tenantStatus != TenantStatus.Active || tariff.State >= TariffState.NotPaid)
                    {
                        context.RequestContext.HttpContext.Response.StatusCode        = (int)HttpStatusCode.PaymentRequired;
                        context.RequestContext.HttpContext.Response.StatusDescription = HttpStatusCode.PaymentRequired.ToString();
                        log.Warn("Payment Required {0}.", context.RequestContext.HttpContext.Request.Url);
                    }
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                return;
            }

            var pid = FindProduct(method);

            if (pid != Guid.Empty)
            {
                if (CallContext.GetData("asc.web.product_id") == null)
                {
                    CallContext.SetData("asc.web.product_id", pid);
                }
                if (!WebItemSecurity.IsAvailableForUser(pid.ToString(), SecurityContext.CurrentAccount.ID))
                {
                    context.RequestContext.HttpContext.Response.StatusCode        = (int)HttpStatusCode.Forbidden;
                    context.RequestContext.HttpContext.Response.StatusDescription = HttpStatusCode.Forbidden.ToString();
                    log.Warn("Product {0} denied for user {1}", method.Name, SecurityContext.CurrentAccount);
                }
            }
        }
Пример #24
0
 private static bool IsGetRequest(IApiMethodCall methodToCall)
 {
     return("get".Equals(methodToCall.HttpMethod, StringComparison.OrdinalIgnoreCase));
 }
 public ApiDuplicateRouteException(IApiMethodCall currentMethod, IApiMethodCall registeredMethod)
     : base(string.Format("route '{0}' is already registered to '{1}'", currentMethod, registeredMethod))
 {
 }
Пример #26
0
 public Route GetRoute(IApiRouteHandler routeHandler, IApiMethodCall method)
 {
     return(GetRoute(routeHandler, method, string.Empty));
 }
Пример #27
0
 public bool Equals(IApiMethodCall other)
 {
     return Equals(other as ApiMethodCall);
 }
Пример #28
0
 public override void ErrorMethodCall(IApiMethodCall method, ASC.Api.Impl.ApiContext context, Exception e)
 {
     Sw.Stop();
     TryLog(LogEntry.Actions.ErrorCall, method, context, e);
     base.ErrorMethodCall(method, context, e);
 }
Пример #29
0
 public virtual void ErrorMethodCall(IApiMethodCall method, ApiContext context, Exception e) { }
Пример #30
0
 public override void PostMethodCall(IApiMethodCall method, ASC.Api.Impl.ApiContext context, object methodResponce)
 {
     Sw.Stop();
     TryLog(LogEntry.Actions.AfterCall, method, context, null);
     base.PostMethodCall(method, context, methodResponce);
 }
 private Guid FindProduct(IApiMethodCall method)
 {
     if (method == null || string.IsNullOrEmpty(method.Name))
     {
         return default(Guid);
     }
     if (method.Name == "community" && !string.IsNullOrEmpty(method.RoutingUrl))
     {
         var module = method.RoutingUrl.Split('/')[0];
         if (products.ContainsKey(module))
         {
             return products[module];
         }
     }
     if (products.ContainsKey(method.Name))
     {
         return products[method.Name];
     }
     return default(Guid);
 }
Пример #32
0
 public virtual void ErrorMethodCall(IApiMethodCall method, ApiContext context, Exception e)
 {
 }
 private XElement ThrowBadDescriptionError(IApiMethodCall apiMethodCall)
 {
     throw new ArgumentException("Bad description for " + apiMethodCall);
 }
Пример #34
0
 private static XElement CreateEmptyParams(IApiMethodCall apiMethodCall)
 {
     return(new XElement("description", apiMethodCall.GetParams().Select(x => new XElement("param", new XAttribute("name", x.Name)))));
 }
Пример #35
0
        public IEnumerable<object> BuildCallingArguments(RequestContext context, IApiMethodCall methodToCall)
        {
            var callArg = new List<object>();
            var requestParams = GetRequestParams(context);

            var methodParams = methodToCall.GetParams().Where(x => !x.IsRetval).OrderBy(x => x.Position);


            foreach (var parameterInfo in methodParams)
            {
                if (requestParams[parameterInfo.Name] != null)
                {
                    //convert
                    var values = requestParams.GetValues(parameterInfo.Name);
                    if (values != null && values.Any())
                    {
                        try
                        {
                            callArg.Add(ConvertUtils.GetConverted(values.First(), parameterInfo));//NOTE; Get first value!
                        }
                        catch (ApiArgumentMismatchException)
                        {
                            //Failed to convert. Try bind
                            callArg.Add(Utils.Binder.Bind(parameterInfo.ParameterType, requestParams, parameterInfo.Name));
                        }
                    }
                }
                else
                {
                    var requestType = string.IsNullOrEmpty(context.HttpContext.Request.ContentType) ? new ContentType("text/plain") : new ContentType(context.HttpContext.Request.ContentType);

                    //try get request param first. It may be form\url-encoded
                    if (!string.IsNullOrEmpty(context.HttpContext.Request[parameterInfo.Name]))
                    {
                        //Drop to
                        callArg.Add(ConvertUtils.GetConverted(context.HttpContext.Request[parameterInfo.Name], parameterInfo));
                    }
                    else if (parameterInfo.ParameterType == typeof(ContentType) && !string.IsNullOrEmpty(context.HttpContext.Request.ContentType))
                    {
                        callArg.Add(new ContentType(context.HttpContext.Request.ContentType));
                    }
                    else if (parameterInfo.ParameterType == typeof(ContentDisposition) && !string.IsNullOrEmpty(context.HttpContext.Request.Headers["Content-Disposition"]))
                    {
                        var disposition = new ContentDisposition(context.HttpContext.Request.Headers["Content-Disposition"]);
                        disposition.FileName = HttpUtility.UrlDecode(disposition.FileName);//Decode uri name
                        callArg.Add(disposition);
                    }
                    else if (parameterInfo.ParameterType.IsSubclassOf(typeof(HttpPostedFile)) && context.HttpContext.Request.Files[parameterInfo.Name] != null)
                    {
                        callArg.Add(context.HttpContext.Request.Files[parameterInfo.Name]);
                    }
                    else if (Utils.Binder.IsCollection(parameterInfo.ParameterType) && parameterInfo.ParameterType.IsGenericType && parameterInfo.ParameterType.GetGenericArguments().First() == typeof(HttpPostedFileBase))
                    {
                        //File catcher
                        var files = new List<HttpPostedFileBase>(context.HttpContext.Request.Files.Count);
                        files.AddRange(from string key in context.HttpContext.Request.Files select context.HttpContext.Request.Files[key]);
                        callArg.Add(files);
                    }
                    else
                    {
                        if (parameterInfo.ParameterType.IsSubclassOf(typeof(Stream)) || parameterInfo.ParameterType == typeof(Stream))
                        {
                            //First try get files
                            var file = context.HttpContext.Request.Files[parameterInfo.Name];
                            callArg.Add(file != null ? file.InputStream : context.HttpContext.Request.InputStream);
                        }
                        else
                        {
                            //Try bind
                            //Note: binding moved here
                            if (IsTypeBindable(parameterInfo.ParameterType))
                            {
                                //Custom type
                                var binded = Utils.Binder.Bind(parameterInfo.ParameterType,
                                    requestParams,
                                    Utils.Binder.IsCollection(parameterInfo.ParameterType) ? parameterInfo.Name : string.Empty);

                                if (binded != null)
                                {
                                    callArg.Add(binded);
                                    continue;//Go to next loop
                                }
                            }
                            //Create null
                            var obj = parameterInfo.ParameterType.IsValueType ? Activator.CreateInstance(parameterInfo.ParameterType) : null;
                            callArg.Add(obj);
                        }


                    }
                }
            }
            return callArg;
        }
 public Route GetPollRoute(IApiRouteHandler routeHandler, IApiMethodCall method)
 {
     return GetPollRoute(routeHandler, method, string.Empty);
 }
 public ApiDuplicateRouteException(IApiMethodCall currentMethod, IApiMethodCall registeredMethod)
     : base(string.Format("route '{0}' is already registered to '{1}'", currentMethod, registeredMethod))
 {
 }
Пример #38
0
 public override void PostMethodCall(IApiMethodCall method, Api.Impl.ApiContext context, object methodResponce)
 {
     method.Responders.Add(Responder); //Resolve type
     //Add serializers to
     base.PostMethodCall(method, context, methodResponce);
 }
 protected string BuildCacheKey(IApiMethodCall methodToCall, IEnumerable<object> callArg, ApiContext context)
 {
     return Container.Resolve<IApiCacheMethodKeyBuilder>().BuildCacheKeyForMethodCall(methodToCall, callArg, context);
 }
 public virtual object InvokeMethod(IApiMethodCall methodToCall, object instance, IEnumerable <object> callArg, ApiContext apicontext)
 {
     return(methodToCall.Invoke(instance, callArg.ToArray()));
 }
 public override void ErrorMethodCall(IApiMethodCall method, ASC.Api.Impl.ApiContext context, Exception e)
 {
     Sw.Stop();
     TryLog(LogEntry.Actions.ErrorCall, method, context,e);
     base.ErrorMethodCall(method, context, e);
 }
Пример #42
0
 private string GetFullPath(string apiBasePathPath, IApiMethodCall apiMethodCall)
 {
     return((apiBasePathPath + apiMethodCall.Name + Config.ApiSeparator +
             apiMethodCall.RoutingUrl.TrimStart(Config.ApiSeparator)).TrimEnd('/'));
 }
Пример #43
0
 public override void PostMethodCall(IApiMethodCall method, Api.Impl.ApiContext context, object methodResponce)
 {
     method.Responders.Add(Responder); //Resolve type
     //Add serializers to
     base.PostMethodCall(method, context, methodResponce);
 }
Пример #44
0
 public virtual void PreMethodCall(IApiMethodCall method,ApiContext context, IEnumerable<object> arguments){}
 public override string BuildCacheKeyForMethodCall(IApiMethodCall apiMethodCall, IEnumerable<object> callArgs, ApiContext context)
 {
     return Core.CoreContext.TenantManager.GetCurrentTenant().TenantId + base.BuildCacheKeyForMethodCall(apiMethodCall,callArgs,context);
 }
Пример #46
0
 public virtual void PostMethodCall(IApiMethodCall method, ApiContext context, object methodResponce){}
Пример #47
0
 public override string BuildCacheKeyForMethodCall(IApiMethodCall apiMethodCall, IEnumerable <object> callArgs, ApiContext context)
 {
     return(Core.CoreContext.TenantManager.GetCurrentTenant().TenantId + base.BuildCacheKeyForMethodCall(apiMethodCall, callArgs, context));
 }
 private static bool IsGetRequest(IApiMethodCall methodToCall)
 {
     return "get".Equals(methodToCall.HttpMethod, StringComparison.OrdinalIgnoreCase);
 }