Пример #1
0
        public async Task <ApiResult> AutoProcessAsync(ApiCall apiCall)
        {
            try
            {
                MethodInfo info;
                if (!_api.TryGetValue(apiCall.Func, out info))
                {
                    return(ApiError.ApiFunctionNotFound(apiCall.Func));
                }

                Task     task;
                object[] parameters = MapParameters(info, apiCall);
                try
                {
                    task = (Task)info.Invoke(this, parameters);
                    await task;
                }
                catch (AutoApiError error)
                {
                    return(new ApiError(error.Message, 400));
                }

                var taskType = typeof(Task);
                var retType  = info.ReturnParameter.ParameterType;
                if (retType == taskType)
                {
                    return(new ApiResult(StdResult.OK));
                }
                else if (retType.IsSubclassOf(taskType) && retType.GenericTypeArguments.Length == 1)
                {
                    // First check whether the function has already returned an ApiResult
                    var apiResultType    = typeof(ApiResult);
                    var genericParamType = retType.GenericTypeArguments[0];
                    if (genericParamType == apiResultType || genericParamType.IsSubclassOf(apiResultType))
                    {
                        var apiResultObj = task.GetType().GetProperty("Result").GetValue(task);
                        return((ApiResult)apiResultObj);
                    }
                    // Ok, so some other object.  Lets wrap it in an ApiResult<T>.
                    var    genericApiResult        = typeof(ApiResult <>);
                    Type[] typeArgs                = { genericParamType };
                    var    contructedApiResultType = genericApiResult.MakeGenericType(typeArgs);
                    var    returnValue             = task.GetType().GetProperty("Result").GetValue(task);
                    var    created = Activator.CreateInstance(contructedApiResultType, new object[] { StdResult.OK, returnValue });
                    return((ApiResult)created);
                }
                else
                {
                    return(ApiError.BadServerApiImplementation(apiCall.Func));
                }
            }
            catch (Exception ex)
            {
                return(ApiError.ServerError(ex.Message));
            }
        }