コード例 #1
0
ファイル: ApiClient.cs プロジェクト: eustachywieczorek/RRR
        /// <summary>
        /// 执行
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method"></param>
        /// <returns></returns>
        /// <exception cref="MethodValidationException"></exception>
        /// <exception cref="NotSupportedException">Method 的 ClientSetupType 对应的类型,没有导出为 IClientSetup </exception>
        public async Task <T> Execute <T>(BaseMethod <T> method)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            if (!this.SetupDic.ContainsKey(method.ClientSetupType))
            {
                throw new NotSupportedException(string.Format("{0} not Export as IClient", method.ClientSetupType.FullName));
            }

            if (!IsInitilized)
            {
                throw new Exception("ApiClient must Init befor use it.");
            }

            //TODO 参数验证
            //var results = method.Validate();
            //if (!results.IsValid) {
            //    var msg = string.Join(";", results.Select(m => m.Message));
            //    this.DealException(method, ErrorTypes.ParameterError, new MethodValidationException(results), msg);
            //    return default(T);
            //}

            var setup = this.SetupDic[method.ClientSetupType];

            if (!setup.IsValid)
            {
                //验证配置
                this.DealException(method, ErrorTypes.SetupError, new ClientSetupException(setup));
                return(default(T));
            }

            try {
                var data = await method.Execute(Option, setup);

                //如果方法设置允许缓存,则保存到缓存
                if (method.AllowCache)
                {
                    await ApiClientCacheProvider.Default.Store(method, data);
                }
                return(data);
            } catch (HttpRequestException ex) {
                this.DealException(method, ErrorTypes.Unknow, ex);
            } catch (ParseException ex) {
                this.DealException(method, ErrorTypes.ParseError, ex);
            } catch (MethodRequestException ex) {
                this.DealException(method, ex.ErrorType, ex);
            } catch (ContentWithErrorException ex) {
                this.DealException(method, ErrorTypes.ResponsedWithErrorInfo, ex);
            } catch (NetworkException ex) {
                this.DealException(method, ErrorTypes.Network, ex);
            } catch (Exception ex) {
                this.DealException(method, ErrorTypes.Unknow, ex);
            }
            return(default(T));
        }
コード例 #2
0
        private void _Start()
        {
            string absoluteUri = request.Uri.AbsolutePath;

            while (absoluteUri.IndexOf("//") >= 0)
            {
                absoluteUri = absoluteUri.Replace("//", "/");
            }

            if (absoluteUri.StartsWith("/api"))
            {
                if (!request.Headers.Contains("Authorization"))
                {
                    RespondWithJSON("Please authenticate", false, 401, new Dictionary <string, string> {
                        { "WWW-Authenticate", "Basic realm=\"CorsairLinkPlusPlus API\"" }
                    });
                    return;
                }

                currentUser = GetCurrentUser(request.Headers["Authorization"]);
                if (currentUser == null)
                {
                    RespondWithJSON("Invalid login", false, 401, new Dictionary <string, string> {
                        { "WWW-Authenticate", "Basic realm=\"CorsairLinkPlusPlus API\"" }
                    });
                    return;
                }

                if (request.HttpMethod == "OPTIONS" || request.HttpMethod == "HEAD")
                {
                    RespondWithJSON("Yep yep, no need for these");
                    return;
                }

                try
                {
                    IDevice device = RootDevice.FindDeviceByPath(absoluteUri.Substring(4));

                    if (device == null)
                    {
                        RespondWithJSON("Device not found", false, 404);
                        return;
                    }

                    if (request.HttpMethod == "POST")
                    {
                        if (currentUser.Value.readOnly)
                        {
                            RespondWithJSON("Your user is read-only", false, 403);
                            return;
                        }

                        JSONMethodCall methodCall;
                        using (StreamReader bodyReader = new StreamReader(request.Body))
                        {
                            methodCall = JsonConvert.DeserializeObject <JSONMethodCall>(bodyReader.ReadToEnd());
                        }
                        BaseMethod.Execute(methodCall.Name, device, methodCall.Params);
                        RespondWithJSON("OK");
                        return;
                    }

                    RespondWithDevice(device);
                    return;
                }
                catch (Exception e)
                {
                    try
                    {
                        RespondWithJSON(e.Message, false, 500);

                        Console.Error.WriteLine("------------------");
                        Console.Error.WriteLine("Error in HTTP");
                        Console.Error.WriteLine(e);
                        Console.Error.WriteLine("------------------");
                    }
                    catch (Exception se)
                    {
                        Console.Error.WriteLine("------------------");
                        Console.Error.WriteLine("Error in HTTP error handler");
                        Console.Error.WriteLine(se);
                        Console.Error.WriteLine("Caused by");
                        Console.Error.WriteLine(e);
                        Console.Error.WriteLine("------------------");
                    }
                    return;
                }
            }
            else
            {
                if (absoluteUri == "/" || absoluteUri == "")
                {
                    absoluteUri = "index.html";
                }
                else
                {
                    absoluteUri = absoluteUri.Substring(1);
                }

                FileInfo fileInfo = new FileInfo(Program.WEB_ROOT_ABSOLUTE + '/' + absoluteUri);

                if (!fileInfo.Exists)
                {
                    RespondWithJSON("Static content not found", false, 404);
                    return;
                }

                if (fileInfo.Attributes.HasFlag(FileAttributes.Directory))
                {
                    RespondWithJSON("Static content is a directory", false, 403);
                    return;
                }

                DirectoryInfo directory = fileInfo.Directory;
                do
                {
                    if (Program.WEB_ROOT_ABSOLUTE.Equals(directory.FullName))
                    {
                        break;
                    }
                    directory = directory.Parent;
                } while (directory != null);

                if (directory == null)
                {
                    RespondWithJSON("Nope, sorry!", false, 403);
                    return;
                }

                string mineType = MIMEAssistant.GetMIMEType(fileInfo.Extension);

                RespondWithRaw(fileInfo.OpenRead(), 200, mineType);
            }
        }