Ejemplo n.º 1
0
        public HttpResponseMessage Login(HttpRequestMessage requestMsg)
        {
            var request = new HttpContextWrapper(HttpContext.Current).Request;

            if (request.Form["username"] == null || request.Form["password"] == null)
            {
                return requestMsg.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    new ArgumentException("Unable to find username or password.")
                );
            }

            var loginDictionnary = this.AuthService.Login(
                request.Form["username"],
                request.Form["password"]
            );

            if (loginDictionnary != null)
            {
                return requestMsg.CreateResponse(
                    HttpStatusCode.OK,
                    loginDictionnary
                );
            }

            return requestMsg.CreateErrorResponse(
                HttpStatusCode.Forbidden,
                "Wrong credentials"
            );
        }
Ejemplo n.º 2
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            const string TOKEN_NAME = "X-Token";

            if (request.Headers.Contains(TOKEN_NAME))
            {
                string encryptedToken = request.Headers.GetValues(TOKEN_NAME).First();
                try
                {
                    Token token = Token.Decrypt(encryptedToken);
                    bool isValidUserId = identityStore.IsValidUserId(token.UserId);
                    bool requestIPMatchesTokenIP = token.IP.Equals(request.GetClientIP());

                    if (!isValidUserId || !requestIPMatchesTokenIP)
                    {
                        HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid indentity or client machine.");
                        return Task.FromResult(reply);
                    }
                }
                catch (Exception ex)
                {
                    HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid token.");
                    return Task.FromResult(reply);
                }
            }
            else
            {
                HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Request is missing authorization token.");
                return Task.FromResult(reply);
            }

            return base.SendAsync(request, cancellationToken);
        }
        protected virtual string ProcessVersionHeader(HttpRequestMessage request, string odataPath)
        {
            var apiVersion = request.Headers.Where(kv => kv.Key.Equals(VersionMap.VersionHeaderName, StringComparison.InvariantCultureIgnoreCase)).SelectMany(kv => kv.Value).FirstOrDefault();

            int version = -1;
            if (string.IsNullOrWhiteSpace(apiVersion))
            {
                version = VersionMap.CurrentVersion;
            }
            else if (!int.TryParse(apiVersion, out version))
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Api Version specified: " + apiVersion));
            }

            if (version < VersionMap.MinVersion || version > VersionMap.CurrentVersion) goto UnsupportedVersion;

            var endpoint = odataPath;

            var targetEndpoint = VersionMap.GetEndpointName(version, endpoint);
            if (targetEndpoint == null) goto UnsupportedVersion;

            return targetEndpoint;
            UnsupportedVersion:
            throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotAcceptable, string.Format("Unsupported Api Version specified: {0}. Current version: {1}",  version, VersionMap.CurrentVersion)));
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpRequestMessage proxiedRequest = null;

            try
            {
                var hostDetails = await apiSettingsData.GetAsync(request.RequestUri);
                if (hostDetails == null)
                {
                    return request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("Host '{0}' not recognised as a valid chaos api", request.RequestUri.Host));
                }

                var apiToForwardToHostName = hostDetails.ForwardApiHostName;

                proxiedRequest = CreateNewRequestToProxiedApi(request, hostDetails, apiToForwardToHostName);

                var client = await CreateHttpClientForProxiedRequest(apiToForwardToHostName);

                return await client.SendAsync(proxiedRequest, cancellationToken);
            }
            catch (TaskCanceledException)
            {
                return cancellationToken.IsCancellationRequested
                           ? request.CreateErrorResponse(HttpStatusCode.RequestTimeout, string.Format("Request forward to '{0}' failed, request timed out", proxiedRequest.RequestUri))
                           : request.CreateErrorResponse(HttpStatusCode.InternalServerError, string.Format("Request forward to '{0}' failed, ", proxiedRequest.RequestUri));
            }
            catch (Exception ex)
            {
                return request.CreateErrorResponse(HttpStatusCode.InternalServerError, string.Format("Request forward to '{0}' failed, {1}", proxiedRequest.RequestUri, ex));
            }
        }
        public static HttpResponseMessage CreateErrorResponse(Exception throwException, HttpRequestMessage request)
        {
            // Here are some examples of how certain exceptions can be mapped to error responses.
            if (throwException is System.ComponentModel.DataAnnotations.ValidationException)
            {
                // Return when the supplied model (command or query) isn't valid.
                return request.CreateResponse<ValidationResult>(HttpStatusCode.BadRequest,
                    ((ValidationException)throwException).ValidationResult);
            }

            if (throwException is OptimisticConcurrencyException)
            {
                // Return when there was a concurrency conflict in updating the model.
                return request.CreateErrorResponse(HttpStatusCode.Conflict, throwException);
            }

            if (throwException is BusinessLayer.CrossCuttingConcerns.AuthorizationException)
            {
                // Return when the current user doesn't have the proper rights to execute the requested operation
                // or to access the requested resource.
                return request.CreateErrorResponse(HttpStatusCode.Unauthorized, throwException);
            }

            if (throwException is System.Collections.Generic.KeyNotFoundException)
            {
                // Return when the requested resource does not exist anymore. Catching a KeyNotFoundException
                // is an example, but you probably shouldn't throw KeyNotFoundException in this case, since it
                // could be thrown for other reasons (such as program errors) in which case this branch should
                // of course not execute.
                return request.CreateErrorResponse(HttpStatusCode.NotFound, throwException);
            }

            // If the throwException can't be handled: return null.
            return null;
        }
        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            Type type;
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            string controllerName = this.GetControllerName(request);
            if (string.IsNullOrEmpty(controllerName))
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                    string.Format("No route providing a controller name was found to match request URI '{0}'",
                    new object[] { request.RequestUri })));
            }
            IEnumerable<string> fullNames = GetControllerFullName(request, controllerName);
            if (fullNames.Count() == 0)
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                        string.Format("No route providing a controller name was found to match request URI '{0}'",
                        new object[] { request.RequestUri })));
            }

            if (this._apiControllerCache.Value.TryGetValue(fullNames.First(), out type))
            {
                return new HttpControllerDescriptor(_configuration, controllerName, type);
            }
            throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                string.Format("No route providing a controller name was found to match request URI '{0}'",
                new object[] { request.RequestUri })));
        }
Ejemplo n.º 7
0
        private HttpResponseMessage Response(HttpRequestMessage request)
        {
            const string defaultPageName = "index.html";
            var path = request.RequestUri.AbsolutePath;
            var suffix = path == string.Empty ? defaultPageName : path.Substring(1);
            var fullPath = Path.Combine(m_BaseFolder, suffix);

            if (!File.Exists(fullPath))
            {
                return request.CreateErrorResponse(
                    HttpStatusCode.NotFound,
                    string.Format("Sorry about that, but there is no file named '{0}' here.", suffix));
            }

            string extension = Path.GetExtension(path);
            FileType fileType;
            if (!m_FileTypes.TryGetValue(extension, out fileType))
            {
                return request.CreateErrorResponse(
                    HttpStatusCode.UnsupportedMediaType,
                    string.Format("Sorry I can not process files like '{0}'.", extension));
            }

            var response = request.CreateResponse();
            var fileStream = new FileStream(fullPath, FileMode.Open);
            response.Content = new StreamContent(fileStream);
            response.Content.Headers.ContentType = fileType.ContentType;
            return response;
        }
        /// <summary>
        /// 以异步操作发送 HTTP 请求到内部管理器以发送到服务器。
        /// </summary>
        /// <returns>
        /// 返回 <see cref="T:System.Threading.Tasks.Task`1"/>。 表示异步操作的任务对象。
        /// </returns>
        /// <param name="request">要发送到服务器的 HTTP 请求消息。</param>
        /// <param name="cancellationToken">取消操作的取消标记。</param>
        /// <exception cref="T:System.ArgumentNullException"> <paramref name="request"/> 为 null。</exception>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var result = EncryptRequest(request);
            if (result != null)
            {
                return result;
            }
            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        var aggregateException = task.Exception;
                        if (aggregateException != null)
                        {
                            var requestException = aggregateException.InnerExceptions.FirstOrDefault(m => m is HttpRequestException);
                            if (requestException != null && requestException.InnerException is WebException)
                            {
                                return request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, requestException.InnerException);
                            }
                        }

                        return request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, task.Exception);
                    }
                    return DecryptResponse(task.Result);
                }, cancellationToken);
        }
Ejemplo n.º 9
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> userNameHeaderValues = null;
            if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_USERID, out userNameHeaderValues))
            {
                if (!IsValidEmissRequest(request))
                {
                    var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not a Valid Request");
                    return Task.FromResult<HttpResponseMessage>(response);
                }

                IEnumerable<String> expireHeaderValues = null;
                if (request.Headers.TryGetValues(KawalDesaHeaders.X_KD_EXPIRES, out expireHeaderValues))
                {
                    if (IsExpiredRequest(expireHeaderValues.FirstOrDefault()))
                    {
                        var response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Your Request Has Expired");
                        return Task.FromResult<HttpResponseMessage>(response);
                    }
                }

                var userName = userNameHeaderValues.First();
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindByName(userName);
                if (user != null)
                {
                    string signature = CryptographyHelper.Sign(request, user.SecretKey);
                    if (signature.Equals(request.Headers.GetValues(KawalDesaHeaders.X_KD_SIGNATURE).FirstOrDefault()))
                    {
                        var identity = new KawalDesaIdentity(user, "Emiss");
                        var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                }
            }
            else if (HttpContext.Current.Session != null && !String.IsNullOrEmpty((string)HttpContext.Current.Session[KawalDesaController.USERID_KEY]))
            {
                var session = HttpContext.Current.Session;
                var userManager = new UserManager<User>(new CUserStore<User>(new DB()));
                var user = userManager.FindById((string)session[KawalDesaController.USERID_KEY]);
                if (user != null)
                {
                    var identity = new KawalDesaIdentity(user, "Session");
                    var principal = new GenericPrincipal(identity, userManager.GetRoles(user.Id).ToArray());
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
            }

            return base.SendAsync(request, cancellationToken);
        }
Ejemplo n.º 10
0
        /// <inheritdoc />
        public override async Task<HttpResponseMessage> ReceiveAsync(string receiver, HttpRequestContext context, HttpRequestMessage request)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.Method == HttpMethod.Post)
            {
                EnsureSecureConnection(request);

                // Read the request entity body
                NameValueCollection data = await ReadAsFormDataAsync(request);

                // Verify that the token is correct
                string token = data[TokenParameter];
                string secretKey = GetWebHookSecret(request, SecretKey, 8, 64);
                if (!WebHookReceiver.SecretEqual(token, secretKey))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, SlackReceiverResources.Receiver_BadToken, TokenParameter);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage invalidCode = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return invalidCode;
                }

                // Get the action
                string action = data[ActionParameter];
                if (string.IsNullOrEmpty(action))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, SlackReceiverResources.Receiver_BadBody, ActionParameter);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage badType = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return badType;
                }

                // Get the subtext by removing the trigger word
                string text = data[TextParameter];
                data[SubtextParameter] = GetSubtext(action, text);

                // Call registered handlers
                return await ExecuteWebHookAsync(receiver, context, request, new string[] { action }, data);
            }
            else
            {
                return CreateBadMethodResponse(request);
            }
        }
Ejemplo n.º 11
0
        /// <inheritdoc />
        public override async Task<HttpResponseMessage> ReceiveAsync(string id, HttpRequestContext context, HttpRequestMessage request)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.Method == HttpMethod.Post)
            {
                // Ensure that we use https and have a valid code parameter
                await EnsureValidCode(request, id);

                // Read the request entity body.
                JObject data = await ReadAsJsonAsync(request);

                // Pick out action from headers
                IEnumerable<string> actions;
                if (!request.Headers.TryGetValues(EventHeaderKey, out actions))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, BitbucketReceiverResources.Receiver_NoEvent, EventHeaderKey);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage noEventHeader = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return noEventHeader;
                }

                // Get the WebHook ID
                IEnumerable<string> webHookId;
                if (!request.Headers.TryGetValues(UUIDHeaderName, out webHookId))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, BitbucketReceiverResources.Receiver_NoId, UUIDHeaderName);
                    context.Configuration.DependencyResolver.GetLogger().Error(msg);
                    HttpResponseMessage noWebHookIdHeader = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                    return noWebHookIdHeader;
                }

                // Set the WebHook ID in the payload
                data[WebHookIdKey] = webHookId.FirstOrDefault();

                // Call registered handlers
                return await ExecuteWebHookAsync(id, context, request, actions, data);
            }
            else
            {
                return CreateBadMethodResponse(request);
            }
        }
Ejemplo n.º 12
0
        public static HttpResponseMessage Process(HttpRequestMessage request)
        {
            // Check if the request contains multipart/form-data.
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            try
            {
                Stream reqStream = request.Content.ReadAsStreamAsync().Result;
                MemoryStream tempStream = new MemoryStream();
                reqStream.CopyTo(tempStream);
                
                tempStream.Seek(0, SeekOrigin.End);
                Log.Submit(LogLevel.Debug, "Upload request has " + tempStream.Length + " bytes");
                tempStream.Position = 0;
                
                StreamContent streamContent = new StreamContent(tempStream);
                foreach (KeyValuePair<string, IEnumerable<string>> header in request.Content.Headers)
                {
                    streamContent.Headers.Add(header.Key, header.Value);
                    Log.Submit(LogLevel.Debug, "Header " + header.Key + ": " + string.Join(",", header.Value));
                }

                MultipartFormDataParser parser = new MultipartFormDataParser(tempStream);

                // This illustrates how to get the file names.
                FilePart file = parser.Files.FirstOrDefault();
                if (parser.Files == null || parser.Files.Count != 1)
                    throw new InvalidOperationException();
                if (file == null || file.FileName != "package")
                    throw new InvalidOperationException();

                PackageDAO.ProcessPackage(file.Data);

                return request.CreateResponse(HttpStatusCode.Created);
            }
            catch (AlreadyExistsException e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.Conflict, e);
            }
            catch (InvalidOperationException e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
            }
            catch (Exception e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
        public HttpResponseMessage GetContactCompany(HttpRequestMessage request, int id)
        {
            var result = this.ContactDao.GetById(id);

            if (result == null) {
                return request.CreateErrorResponse(HttpStatusCode.NotFound, "Contact not found.");
            }

            return result.Company != null
                ? request.CreateResponse(HttpStatusCode.OK, result.Company)
                : request.CreateErrorResponse(HttpStatusCode.NotFound, "This contact has no company");
        }
        public HttpResponseMessage Post(HttpRequestMessage request, Order order)
        {
            if (!order.Items.Any())
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Order has no items");

            if(_orderService.Exists(order.Id))
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Order already exists");

            _orderService.Save(order);
            var response = request.CreateResponse(HttpStatusCode.Created);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = order.Id }));
            return response;
        }
Ejemplo n.º 15
0
        public HttpResponseMessage AddCategory(HttpRequestMessage req, RP_AddCategory rpAddCategory)
        {
            if (rpAddCategory != null)
            {
                RM_AddCategory rmAddCategory = new RM_AddCategory();
                List<RPR_AddCategory> rprAddCategory = rmAddCategory.AddCategory(rpAddCategory);

                if (rmAddCategory._IsSuccess)
                    return req.CreateResponse<List<RPR_AddCategory>>(HttpStatusCode.Created, rprAddCategory);

                return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "ServerError");
            }

            return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request");
        }
Ejemplo n.º 16
0
        public HttpResponseMessage AddHappyHours(HttpRequestMessage req, Rp_AddHappyHours rpAddHappyHours)
        {
            if (rpAddHappyHours != null)
            {
                RM_AddHappyHours rmAddHappyHours = new RM_AddHappyHours();
                List<RPR_AddHappyHours> rprAddHappyHours = rmAddHappyHours.AddHappyHours(rpAddHappyHours);

                if (rmAddHappyHours._IsSuccess)
                    return req.CreateResponse<List<RPR_AddHappyHours>>(HttpStatusCode.Created, rprAddHappyHours);

                return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "ServerError");
            }

            return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request");
        }
Ejemplo n.º 17
0
        public HttpResponseMessage ChangeOrderStatus(HttpRequestMessage req, RP_ChangeOrderStatus rpChangeOrderStatus)
        {
            if (rpChangeOrderStatus != null)
            {
                RM_ChangeOrderStatus rmChangeOrderStatus = new RM_ChangeOrderStatus();
                List<RPR_ChangeOrderStatus> rprChangeOrderStatus = rmChangeOrderStatus.ChangeOrderStatus(rpChangeOrderStatus);

                if (rmChangeOrderStatus._IsSuccess)
                    return req.CreateResponse<List<RPR_ChangeOrderStatus>>(HttpStatusCode.Created, rprChangeOrderStatus);

                return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "ServerError");
            }

            return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request");
        }
Ejemplo n.º 18
0
        protected IHttpActionResult ConsumeExceptionFromStore(HttpRequestMessage req, AggregateException ex)
        {
            if (req!=null && ex !=null) {
                HttpStatusCode code = HttpStatusCode.InternalServerError;

                if (ex.InnerException is IOException) {
                    code = HttpStatusCode.InternalServerError;
                }
                else if (ex.InnerException is ArgumentException) {
                    code = HttpStatusCode.BadRequest;
                }
                return ResponseMessage(req.CreateErrorResponse(code, ex.InnerException.Message));
            }
            return ResponseMessage(req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unexpected error while consuming the exception from the store"));
        }
Ejemplo n.º 19
0
        public HttpResponseMessage CancelOrder(HttpRequestMessage req, RP_CancelOrder rpCancelOrder)
        {
            if (rpCancelOrder != null)
            {
                RM_CancelOrder rmCancelOrder = new RM_CancelOrder();
                List<RPR_CancelOrder> rprCancelOrder = rmCancelOrder.CancelOrder(rpCancelOrder);

                if (rmCancelOrder._IsSuccess)
                    return req.CreateResponse<List<RPR_CancelOrder>>(HttpStatusCode.Created, rprCancelOrder);

                return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "ServerError");
            }

            return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request");
        }
Ejemplo n.º 20
0
        public HttpResponseMessage AllowToJoinTable(HttpRequestMessage req, RP_AllowToJoinTable rpAllowToJoinTable)
        {
            if (rpAllowToJoinTable != null)
            {
                RM_AllowToJoinTable rmAllowToJoinTable = new RM_AllowToJoinTable();
                List<RPR_AllowToJoinTable> rprAllowToJoinTable = rmAllowToJoinTable.AllowToJoinTable(rpAllowToJoinTable);

                if (rmAllowToJoinTable._IsSuccess)
                    return req.CreateResponse<List<RPR_AllowToJoinTable>>(HttpStatusCode.Created, rprAllowToJoinTable);

                return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "ServerError");
            }

            return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request");
        }
Ejemplo n.º 21
0
        public HttpResponseMessage AddedToCart(HttpRequestMessage req, RP_AddedToCart rpAddedToCart)
        {
            if (rpAddedToCart != null)
            {
                RM_AddedToCart rmAddedToCart = new RM_AddedToCart();
                List<RPR_AddedToCart> rprAddedToCart = rmAddedToCart.AddedToCart(rpAddedToCart);

                if (rmAddedToCart._IsSuccess)
                    return req.CreateResponse<List<RPR_AddedToCart>>(HttpStatusCode.Created, rprAddedToCart);

                return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "ServerError");
            }

            return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad Request");
        }
Ejemplo n.º 22
0
        public HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            var routeData = request.GetRouteData();
            var module = request.FindModuleInfo();

            // Handle the app-api queries
            if (routeData.Route.RouteTemplate.Contains("DesktopModules/2sxc/API/app-api/") && module.DesktopModule.ModuleName == "2sxc-app")
            {
                var portalSettings = PortalSettings.Current;
                var sexy = request.GetSxcOfModuleContext();

                // previously we assumed that there is a sub-folder with a future-app-id, but 2015-05-15 decided it's probably not worth trying, because each request currently needs tokens anyhow
                // if ((string) routeData.Values["appFolder"] != "auto-detect-app" && (string) routeData.Values["appFolder"] != sexy.App.Folder)
                //    throw new HttpException("AppFolder was not correct - was " + routeData.Values["appFolder"] + " but should be " + sexy.App.Folder);

                var controllerTypeName = routeData.Values["controller"] + "Controller";

                var controllerPath = Path.Combine(SexyContent.AppBasePath(portalSettings), sexy.App.Folder,
                    "Api/" + controllerTypeName + ".cs");

                if (File.Exists(HostingEnvironment.MapPath(controllerPath)))
                {
                    var assembly = BuildManager.GetCompiledAssembly(controllerPath);
                    var type = assembly.GetType(controllerTypeName);
                    return new HttpControllerDescriptor(_config, controllerTypeName, type);
                }
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, "Controller " + controllerTypeName + " not found in app."));
            }
            return PreviousSelector.SelectController(request);
        }
        public override string GetControllerName(System.Net.Http.HttpRequestMessage request)
        {
            string controllerName = base.GetControllerName(request);
            int    controllerVersion;

            if (request.Headers.Contains("X-Version"))
            {
                string headerValue = request.Headers.GetValues("X-Version").First();
                if (headerValue == "0")
                {
                    return(controllerName);
                }

                if (!String.IsNullOrEmpty(headerValue) && Int32.TryParse(headerValue, out controllerVersion))
                {
                    controllerName = String.Format("{0}v{1}", controllerName, controllerVersion);
                    HttpControllerDescriptor controllerDescr = null;
                    if (!this.GetControllerMapping().TryGetValue(controllerName, out controllerDescr))
                    {
                        string message = "No HTTP resource was found for specified request URI {0} and version {1}";
                        throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format(message, request.RequestUri, controllerVersion)));
                    }
                }
            }
            return(controllerName);
        }
Ejemplo n.º 24
0
        public async Task<HttpResponseMessage> Get(HttpRequestMessage request, [FromUri(Name = "objectContext")]string userId)
        {
            try
            {
                // Call the execution pipeline and get the result
                IBackloadResult result = await _handler.Execute();

                // Get the client plugin specific result
                var clientResult = ((IFileStatusResult)result).ClientStatus;

                // return result object and status code
                return request.CreateResponse(result.HttpStatusCode, clientResult);


                #region Optional: Use Backload Api (Services namespace. Pro/Enterprise only) 

                //// Simple demo: Call the GET execution method and get the result
                //IFileStatus status = await _handler.Services.GET.Execute();

                //// Create plugin specific result
                //result = _handler.Services.Core.CreatePluginResult();

                //// return plugin specific result object
                //return request.CreateResponse(HttpStatusCode.OK, result.ClientStatus);

                #endregion Optional: Use backload Api (Services namespace. Pro/Enterprise only)

            }
            catch(Exception e)
            {
                return request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
Ejemplo n.º 25
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Lookup route data, or if not found as a request property then we look it up in the route table
            IHttpRouteData routeData;
            if (!request.Properties.TryGetValue(HttpPropertyKeys.HttpRouteDataKey, out routeData))
            {
                routeData = _configuration.Routes.GetRouteData(request);

                if (routeData != null)
                {
                    request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
                }
                else
                {
                    request.Properties.Add(HttpPropertyKeys.NoRouteMatched, true);
                    return TaskHelpers.FromResult(request.CreateErrorResponse(
                        HttpStatusCode.NotFound,
                        Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                        SRResources.NoRouteData));
                }
            }

            RemoveOptionalRoutingParameters(routeData.Values);

            // routeData.Route could be null if user adds a custom route that derives from System.Web.Routing.Route explicitly 
            // and add that to the RouteCollection in the web hosted case
            var invoker = (routeData.Route == null || routeData.Route.Handler == null) ?
                _defaultInvoker : new HttpMessageInvoker(routeData.Route.Handler, disposeHandler: false);
            return invoker.SendAsync(request, cancellationToken);
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var setting = Its.Configuration.Settings.Get<Config.SwaggerToolSettings>();
            //using refletions to internal
            var swaggerProvider = (ISwaggerProvider)_config.GetType().GetMethod("GetSwaggerProvider", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(_config, new object[] { request });

            var rootUrl = (string)_config.GetType().GetMethod("GetRootUrl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(_config, new object[] { request });
            var q = request.GetRouteData().Values["q"].ToString();
            var apiVersion = request.GetRouteData().Values["apiVersion"].ToString();

            try
            {
                var swaggerDoc = swaggerProvider.GetSwagger(rootUrl, apiVersion);

                //筛选条件为path包含q
                IList<string> keytoremove = new List<string>();
                foreach (var item in swaggerDoc.paths)
                {
                    if (!item.Key.ToUpper().Contains(q.ToUpper()))
                    {
                        keytoremove.Add(item.Key);
                    }
                }
                foreach (var item in keytoremove)
                {
                    swaggerDoc.paths.Remove(item);
                }
                var content = ContentFor(request, swaggerDoc);
                return TaskFor(new HttpResponseMessage { Content = content });
            }
            catch (UnknownApiVersion ex)
            {
                return TaskFor(request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }
        }
Ejemplo n.º 27
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Lookup route data, or if not found as a request property then we look it up in the route table
            IHttpRouteData routeData;
            if (!request.Properties.TryGetValue(HttpPropertyKeys.HttpRouteDataKey, out routeData))
            {
                routeData = _configuration.Routes.GetRouteData(request);
                if (routeData != null)
                {
                    request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
                }
                else
                {
                    return TaskHelpers.FromResult(request.CreateErrorResponse(
                        HttpStatusCode.NotFound,
                        Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                        SRResources.NoRouteData));
                }
            }

            RemoveOptionalRoutingParameters(routeData.Values);

            var invoker = routeData.Route.Handler == null ? _defaultInvoker : new HttpMessageInvoker(routeData.Route.Handler, disposeHandler: false);
            return invoker.SendAsync(request, cancellationToken);
        }
Ejemplo n.º 28
0
 private Task<HttpResponseMessage> GenerateUnauthorizedResponse(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     var unauthorizedResponse = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized origin.");
     var tsc = new TaskCompletionSource<HttpResponseMessage>();
     tsc.SetResult(unauthorizedResponse);
     return tsc.Task;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation.
        /// </summary>
        /// <param name="request">The HTTP request message to send to the server.</param>
        /// <param name="cancellationToken">A cancellation token to cancel operation.</param>
        /// <returns>
        /// Returns <see cref="T:System.Threading.Tasks.Task`1" />. The task object representing the asynchronous operation.
        /// </returns>
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var queryParams = HttpUtility.ParseQueryString(request.RequestUri.Query);
            var acceptValue = queryParams.Get("accept");
            if (acceptValue != null)
            {
                request.Headers.Accept.Clear();
                request.Headers.Accept.ParseAdd(acceptValue);
            }

            var fieldsValue = queryParams.Get("fields");
            if (fieldsValue != null)
            {
            }

            var methodValue = queryParams.Get("method");
            if (methodValue != null)
            {
                try
                {
                    request.Method = ToMethod(methodValue);
                }
                catch (UnknownHttpMethodException ex)
                {
                    return request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
                }
            }

            return await base.SendAsync(request, cancellationToken);
        }
Ejemplo n.º 30
0
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var resource = ((string)request.GetRouteData().Values["controller"]).ToLower();
            var action = request.GetRouteData().Values.ContainsKey("action") ? ((string)request.GetRouteData().Values["action"]).ToLower() : null;
            var method = request.Method.ToString().ToUpper();

            var securityToken = GetToken(request);
            try
            {
                _authenticationService.ValidateAccess(securityToken, resource, action, method);
            }
            catch (UnauthorizedException ex)
            {
                return request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
            }

            SaveContext(request, _authenticationService);

            var response = await base.SendAsync(request, cancellationToken);

            UpdateContext(request, _authenticationService);

            securityToken = _authenticationService.CreateToken();

            if (securityToken != null)
                AddTokenToHeader(response, securityToken);

            return response;
        }
Ejemplo n.º 31
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            if(request.Headers.Any(a=>a.Key == MasterPasswordHeader))
            {
                var passwordHeader = request.Headers.First(a => a.Key == MasterPasswordHeader);
                var passwordHash = passwordHeader.Value.FirstOrDefault();
                if (passwordHash == ConfigurationManager.AppSettings[MasterPasswordHashAppConfigKey])
                {
                    IPrincipal principal = new GenericPrincipal(
                        new GenericIdentity(Roles.Elevated),
                        new string[] { Roles.Elevated });
                    Thread.CurrentPrincipal = principal;
                    if (HttpContext.Current!=null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
                else
                {
                    return Task.Factory.StartNew(() => request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid password"));
                }

            }

            return base.SendAsync(request, cancellationToken);
        }
Ejemplo n.º 32
0
        public HttpResponseMessage Get(string email, string senha)
        {
            var configuration = new HttpConfiguration();
            var request       = new System.Net.Http.HttpRequestMessage();

            request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

            try
            {
                var usuario = _loginAppService.Login(email, senha);

                return(request.CreateResponse(HttpStatusCode.OK, usuario));
            }
            catch (Exception e)
            {
                return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message));
            }
        }
Ejemplo n.º 33
0
        public HttpControllerDescriptor SelectController(System.Net.Http.HttpRequestMessage request)
        {
            System.Web.Http.Routing.IHttpRouteData routeData = request.GetRouteData();
            if (routeData == null)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }

            string version = GetRouteVariable <string>(routeData, VersionKey);

            if (string.IsNullOrEmpty(version))
            {
                version = GetVersionFromHTTPHeaderAndAcceptHeader(request);
            }
            string controllerName = GetRouteVariable <string>(routeData, ControllerKey);

            if (controllerName == null)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }

            string key = String.Format(CultureInfo.InvariantCulture, "{0}", controllerName);

            if (!string.IsNullOrEmpty(version))
            {
                key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", version, controllerName);
            }
            HttpControllerDescriptor controllerDescriptor;

            if (_controllers.Value.TryGetValue(key, out controllerDescriptor))
            {
                return(controllerDescriptor);
            }
            else if (_duplicates.Contains(key))
            {
                throw new HttpResponseException(
                          request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                                                      "Multiple controllers were found that match this request."));
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }
Ejemplo n.º 34
0
        public HttpResponseMessage Post(UsuarioViewModel usuarioViewModel)
        {
            var configuration = new HttpConfiguration();
            var request       = new System.Net.Http.HttpRequestMessage();

            request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

            try
            {
                var usuario = _usuarioAppService.Adicionar(usuarioViewModel);

                var telefoneViewModel = new TelefoneViewModel();

                foreach (var telefone in usuario.Telefones)
                {
                    // Adicionando os dados do telefone

                    telefoneViewModel.Id        = Guid.NewGuid();
                    telefoneViewModel.Numero    = telefone.Numero;
                    telefoneViewModel.Ddd       = telefone.Ddd;
                    telefoneViewModel.UsuarioId = usuario.Id;

                    // chamanda o serviço para adicionar o telefone

                    _telefoneAppService.AdicionarTelefone(telefoneViewModel);

                    // Adicionando dados do telefone para retorno

                    telefone.Id        = telefoneViewModel.Id;
                    telefone.UsuarioId = telefoneViewModel.UsuarioId;
                }

                return(request.CreateResponse(HttpStatusCode.OK, usuario));
            }
            catch (Exception e)
            {
                return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message));
            }
        }
Ejemplo n.º 35
0
        public HttpResponseMessage Get(Guid id)
        {
            var configuration = new HttpConfiguration();
            var request       = new System.Net.Http.HttpRequestMessage();

            request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

            // Buscando o Header de Autorização

            var authorization = Request.Headers.Authorization;

            var token = authorization.ToString();

            try
            {
                var usuario = _profilerAppService.ValidarToken(token, id);

                return(request.CreateResponse(HttpStatusCode.OK, usuario));
            }
            catch (Exception e)
            {
                return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message));
            }
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage"/> representing an error
 /// with an instance of <see cref="ObjectContent{T}"/> wrapping an <see cref="HttpError"/> with message <paramref name="message"/>
 /// and message detail <paramref name="messageDetail"/>.If no formatter is found, this method returns a response with
 /// status 406 NotAcceptable.
 /// </summary>
 /// <remarks>
 /// This method requires that <paramref name="request"/> has been associated with an instance of
 /// <see cref="HttpConfiguration"/>.
 /// </remarks>
 /// <param name="request">The request.</param>
 /// <param name="statusCode">The status code of the created response.</param>
 /// <param name="message">The error message. This message will always be seen by clients.</param>
 /// <param name="messageDetail">The error message detail. This message will only be seen by clients if we should include error detail.</param>
 /// <returns>An error response with error message <paramref name="message"/> and message detail <paramref name="messageDetail"/>
 /// and status code <paramref name="statusCode"/>.</returns>
 internal static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, string messageDetail)
 {
     return(request.CreateErrorResponse(statusCode, includeErrorDetail => includeErrorDetail ? new HttpError(message, messageDetail) : new HttpError(message)));
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage"/> representing an error
 /// with an instance of <see cref="ObjectContent{T}"/> wrapping an <see cref="HttpError"/> with message <paramref name="message"/>.
 /// If no formatter is found, this method returns a response with status 406 NotAcceptable.
 /// </summary>
 /// <remarks>
 /// This method requires that <paramref name="request"/> has been associated with an instance of
 /// <see cref="HttpConfiguration"/>.
 /// </remarks>
 /// <param name="request">The request.</param>
 /// <param name="statusCode">The status code of the created response.</param>
 /// <param name="message">The error message.</param>
 /// <returns>An error response with error message <paramref name="message"/> and status code <paramref name="statusCode"/>.</returns>
 public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message)
 {
     return(request.CreateErrorResponse(statusCode, new HttpError(message)));
 }
        public void CreateErrorResponseRangeNotSatisfiable_ThrowsOnNullException()
        {
            HttpRequestMessage request = new HttpRequestMessage();

            Assert.ThrowsArgumentNull(() => request.CreateErrorResponse(invalidByteRangeException: null), "invalidByteRangeException");
        }