public HttpResponseMessage DeleteApplication([FromBody] ApplicationRequest request) { HttpResponseContent responseContent = manager.ValidateDeletion(request); HttpResponseMessage response = Request.CreateResponse(responseContent.Code, responseContent.Message); return(response); }
/// <summary> /// Gets the request data from the client. /// </summary> /// <param name="context">Provides access to the request and response objects.</param> /// <returns>The array of request bytes</returns> public virtual byte[] GetRequestData(IHttpContext context) { System.IO.Stream inputRequest = null; System.IO.MemoryStream memoryOutput = null; HttpListenerRequest httpRequest = null; try { // Get the request and response context. httpRequest = context.HttpContext.Request; // Read the request stream data and write // to the memory stream. inputRequest = httpRequest.InputStream; memoryOutput = new System.IO.MemoryStream(); HttpResponseContent.TransferData(inputRequest, memoryOutput); // Properly flush and close the output stream inputRequest.Flush(); memoryOutput.Flush(); inputRequest.Close(); memoryOutput.Close(); // Get the request data. byte[] requestData = memoryOutput.ToArray(); // Return the request data. return(requestData); } catch (Exception) { throw; } finally { try { if (inputRequest != null) { inputRequest.Close(); } } catch { } try { if (memoryOutput != null) { memoryOutput.Close(); } } catch { } } }
public HttpResponseMessage UpdateApplication([FromBody] ApplicationRequest request) { using (var _db = new DatabaseContext()) { IApplicationManager manager = new ApplicationManager(_db); HttpResponseContent responseContent = manager.ValidateUpdate(request); HttpResponseMessage response = Request.CreateResponse(responseContent.Code, responseContent.Message); return(response); } }
public IHttpActionResult Register([FromBody] ApplicationRequest request) { HttpResponseContent responseContent = new HttpResponseContent(); // Body of Response Message if (!ModelState.IsValid || request == null) { // 412 Response responseContent.Code = HttpStatusCode.PreconditionFailed; responseContent.Message = "Invalid Request"; return(Content(responseContent.Code, responseContent)); } try { using (var _db = new DatabaseContext()) { IApplicationManager manager = new ApplicationManager(_db); // Validate request and register application responseContent = manager.ValidateRegistration(request); } responseContent.Code = HttpStatusCode.OK; } catch (Exception ex) { // Request inputs are invalid format or violate business rules if (ex is InvalidStringException || ex is InvalidEmailException || ex is InvalidUrlException || ex is ArgumentException) { responseContent.Code = HttpStatusCode.BadRequest; } // Error in data store else if (ex is DbEntityValidationException) { responseContent.Code = HttpStatusCode.InternalServerError; } else { responseContent.Code = HttpStatusCode.InternalServerError; } responseContent.Message = ex.Message; } return(Content(responseContent.Code, responseContent)); }
/// <summary> /// The page is loading. /// </summary> /// <param name="pageContext">The page content.</param> public override void OnLoad(HttpPageContext pageContext) { bool deleteFiles = true; bool deleteDirectories = true; // Get the download file directory. string directoryQuery = ""; if (base.Request.QueryString != null) { if (!string.IsNullOrEmpty(base.Request.QueryString["directory"])) { directoryQuery = base.Request.QueryString["directory"]; } // If the delete file query exists if (!String.IsNullOrEmpty(base.Request.QueryString["deletefile"])) { // Get the file to delete path. string fileNameToDelete = base.UploadDirectory + base.Request.QueryString["deletefile"].Replace("/", "\\"); // If the file exists then delete the file. if (System.IO.File.Exists(fileNameToDelete)) { System.IO.File.Delete(fileNameToDelete); } } // If the delete directory query exists if (!String.IsNullOrEmpty(base.Request.QueryString["deletedirectory"])) { // Get the directory to delete path. string directoryToDelete = base.UploadDirectory + base.Request.QueryString["deletedirectory"].Replace("/", "\\").TrimStart('\\') + "\\"; // If the directory exists then delete the directory. if (System.IO.Directory.Exists(directoryToDelete)) { System.IO.Directory.Delete(directoryToDelete, true); } } } // Get the file system html. base.AlternativeContent = HttpResponseContent.UploadFileList(base.Response, base.UploadDirectory, System.IO.Path.GetFileName(base.UrlFilePath), directoryQuery, deleteFiles, deleteDirectories); }
/// <summary> /// Sens the response data to the client. /// </summary> /// <param name="context">Provides access to the request and response objects.</param> /// <param name="response">The array of response bytes.</param> public virtual void SendResponseData(IHttpContext context, byte[] response) { System.IO.Stream outputResponse = null; System.IO.MemoryStream memoryInput = null; HttpListenerResponse httpResponse = null; try { // Get the request and response context. httpResponse = context.HttpContext.Response; // Create the response. memoryInput = HttpResponseContent.CreateResponseStream(response); // Transfer the data. outputResponse = httpResponse.OutputStream; HttpResponseContent.TransferResponse(memoryInput, outputResponse); } catch (Exception) { throw; } finally { try { if (outputResponse != null) { outputResponse.Close(); } } catch { } try { if (memoryInput != null) { memoryInput.Close(); } } catch { } } }
/// <summary> /// The page hierachy initialiser. /// </summary> /// <param name="page">The current page instance.</param> /// <param name="urlFilePath">The local file name and full path of the resource.</param> /// <param name="context">Provides access to the request and response objects.</param> public static void PageInitialiser(HttpPageBase page, string urlFilePath, IHttpContext context) { // Make sure that the page exists. if (page != null) { System.IO.Stream outputResponse = null; System.IO.Stream inputRequest = null; try { // Create a new page context. HttpPageContext pageContext = new HttpPageContext(); pageContext.IsValid = true; pageContext.OverrideRequestResponse = false; pageContext.ProcessOnPostBack = true; // Assign the initial values. page.Request = context.HttpContext.Request; page.Response = context.HttpContext.Response; page.IsPostBack = context.ActiveProcess.IsPostBack; page.UrlFilePath = urlFilePath; page.User = context.HttpContext.User; // Execute the page hierachy. page.OnInit(pageContext); // If true then continue if (pageContext.IsValid) { // Assign the current active processing. page.ActiveProcessing = context.ActiveProcess; // Execute the pre-processing event. page.OnPreProcess(pageContext); if (pageContext.ProcessOnPostBack) { // If post back. if (context.ActiveProcess.IsPostBack) { // Get all the post back data. context.ActiveProcess.ProcessPostBack(page.Request, page.UploadDirectory); page.Form = context.ActiveProcess.Form; page.UploadFiles = context.ActiveProcess.UploadFiles; } } // Execute the page load event. page.OnLoad(pageContext); if (!pageContext.OverrideRequestResponse) { // If alternative content is to be sent. if (page.AlternativeContent != null) { // Get the request, response stream. outputResponse = context.HttpContext.Response.OutputStream; // Transfer the data to the client. inputRequest = HttpResponseContent.CreateResponseStream(page.AlternativeContent); HttpResponseContent.TransferResponse(inputRequest, outputResponse); } else { // Get the request, response stream. outputResponse = context.HttpContext.Response.OutputStream; // Get the response html. Create the response. Transfer the data. byte[] responseResourceHtmlData = HttpResponseContent.ResourceFound(context.HttpContext.Response, context.ActiveProcess, urlFilePath, System.IO.Path.GetExtension(urlFilePath).TrimStart('.')); // Transfer the data to the client. inputRequest = HttpResponseContent.CreateResponseStream(responseResourceHtmlData); HttpResponseContent.TransferResponse(inputRequest, outputResponse); } } } } catch (Exception) { throw; } finally { try { if (inputRequest != null) { inputRequest.Close(); } } catch (Exception ex) { page.Exception = ex; } try { if (outputResponse != null) { outputResponse.Close(); } } catch (Exception ex) { page.Exception = ex; } } } }
public async Task <HttpRequestSenderResponse> SendAsync(HttpRequestSenderInput input, CancellationToken cancellationToken) { HttpRequestSenderResponse result = null; using (var msg = BuildMessage(input)) { using (var httpResponse = await _client.SendAsync(msg, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) { result = BuildRequestResponse(httpResponse); var isSucceed = httpResponse.IsSuccessStatusCode; if (isSucceed && input.OnSuccess == null) { HttpRequestLog.Trace("Response succeed and no handler for success defined. so returning basic response"); return(result); } if (!isSucceed && input.OnFailure == null) { HttpRequestLog.Trace("Failed response and no handler for failure defined. so returning basic response"); return(result); } if (httpResponse.Content == null) { HttpRequestLog.Trace("Content empty so returning basic response"); return(result); } var rsp = new HttpResponseContent { ContentLength = httpResponse.Content.Headers.ContentLength ?? 0, StatusCode = httpResponse.StatusCode, ContentType = httpResponse.Content.Headers.ContentType?.MediaType, Headers = result.Headers }; using (httpResponse.Content) { using (var sr = await httpResponse.Content.ReadAsStreamAsync()) { rsp.ContentStream = sr; rsp.StatusCode = httpResponse.StatusCode; if (isSucceed) { HttpRequestLog.Trace("Executing success handler"); await input.OnSuccess(rsp); } else { HttpRequestLog.Trace("Executing failure handler"); await input.OnFailure(rsp); } } } } } return(result); }
/// <summary> /// Process the http server resource request. /// </summary> /// <param name="context">Provides access to the request and response objects.</param> public virtual void HttpServiceProcessRequest(IHttpContext context) { System.IO.Stream outputResponse = null; System.IO.Stream inputRequest = null; System.IO.MemoryStream memoryOutput = null; System.IO.MemoryStream memoryInput = null; HttpListenerRequest httpRequest = null; HttpListenerResponse httpResponse = null; try { // Get the upload file directory. string serviceDirectory = BaseServicePath.TrimEnd('\\') + "\\"; string uploadFilePath = null; bool foundInDownload = false; // Get the request and response context. httpRequest = context.HttpContext.Request; httpResponse = context.HttpContext.Response; // Get the current resposne stream. outputResponse = httpResponse.OutputStream; // Get the current request filename and directory information. string absolutePath = HttpUtility.UrlDecode(httpRequest.Url.AbsolutePath.TrimStart('/').Replace("/", "\\")); string urlFilePath = serviceDirectory + absolutePath; bool fileExists = System.IO.File.Exists(urlFilePath); // Look in the base download path for the file. if (!fileExists) { // If an upload path has been supplied. if (!string.IsNullOrEmpty(BaseUploadPath)) { // Get the upload directory. string uploadDirectory = BaseUploadPath.TrimEnd('\\') + "\\"; string[] directories = Path.GetDirectoryName(absolutePath).Split(new char[] { '\\' }); // Get the directory query string. string directory = ""; bool foundStart = false; foreach (string item in directories) { // Find the starting virtual directory name associated // with the current service name. if (item.ToLower() == _serviceVirtualName.ToLower()) { foundStart = true; } // Build the directory. if (foundStart) { directory += item + "\\"; } } // Get the download file path. uploadFilePath = uploadDirectory + (string.IsNullOrEmpty(directory) ? "" : directory.ToLower().Replace(_serviceVirtualName.ToLower() + "\\", "").TrimEnd('\\') + "\\") + System.IO.Path.GetFileName(urlFilePath); // Does the file exist. fileExists = System.IO.File.Exists(uploadFilePath); // If the file is found in the download path. if (fileExists) { foundInDownload = true; } } } // If the file does not exists then try to load // the default.htm file. if (!fileExists) { string newUrlFilePath = urlFilePath.TrimEnd('\\') + "\\"; string newFileName = System.IO.Path.GetFileName(newUrlFilePath); // Create the new default url file name. if (String.IsNullOrEmpty(newFileName)) { urlFilePath = newUrlFilePath + "default.htm"; fileExists = System.IO.File.Exists(urlFilePath); } } // Does the resource exits on the server. if (fileExists) { // Get the extension of the resource. string extension = System.IO.Path.GetExtension(urlFilePath).TrimStart(new char[] { '.' }); string fileName = System.IO.Path.GetFileName(urlFilePath); string[] extensions = context.ActiveProcess.AllowedExtensions(); // Get the maximum upload file size. int maxUploadFileSize = MaxBaseContentSize; // If the file is not too large. if (httpRequest.ContentLength64 >= maxUploadFileSize) { // Get the response html. Create the response. Transfer the data. byte[] responseMaxHtmlData = HttpResponseContent.MaxContentLength(httpResponse, maxUploadFileSize); HttpResponseContent.TransferResponse(HttpResponseContent.CreateResponseStream(responseMaxHtmlData), outputResponse); } else { // Extension is allowed and the resource is // not a download file. if (extensions.Count(u => u.Contains(extension)) > 0 && !foundInDownload) { // Execute the correct page code behind. bool ret = HttpPageBase.PageInstance(BaseNameSpace, AssemblyName, urlFilePath, context); // If the resource code behind does not exist // then load only the content data. if (!ret) { // If no code behind then load the resource. byte[] responseResourceHtmlData = HttpResponseContent.ResourceFound(httpResponse, context.ActiveProcess, urlFilePath, extension); HttpResponseContent.TransferResponse(HttpResponseContent.CreateResponseStream(responseResourceHtmlData), outputResponse); } } else { // Get the response html. Create the response. Transfer the data. byte[] responseFoundAttachmentHtmlData = HttpResponseContent.ResourceAttachment(httpResponse, uploadFilePath, extension, fileName); HttpResponseContent.TransferResponse(HttpResponseContent.CreateResponseStream(responseFoundAttachmentHtmlData), outputResponse); } } } else { // Get the response html. Create the response. Transfer the data. byte[] responseNotFoundHtmlData = HttpResponseContent.FileNotFound(httpResponse); HttpResponseContent.TransferResponse(HttpResponseContent.CreateResponseStream(responseNotFoundHtmlData), outputResponse); } } catch (Exception ex) { try { if (httpResponse != null) { // Get the response html. Create the response. Transfer the data. byte[] responseErrorHtmlData = HttpResponseContent.OnError(httpResponse, ex); memoryInput = HttpResponseContent.CreateResponseStream(responseErrorHtmlData); // If the response stream has already been activated. if (outputResponse == null) { // Transfer the data. outputResponse = httpResponse.OutputStream; HttpResponseContent.TransferResponse(memoryInput, outputResponse); } else { // Send the response. HttpResponseContent.TransferResponse(memoryInput, outputResponse); } } } catch { } throw; } finally { try { if (inputRequest != null) { inputRequest.Close(); } } catch { } try { if (outputResponse != null) { outputResponse.Close(); } } catch { } try { if (memoryOutput != null) { memoryOutput.Close(); } } catch { } try { if (memoryInput != null) { memoryInput.Close(); } } catch { } } }
/// <summary> /// 校验请求 /// </summary> /// <param name="context"></param> public async void ValidateResponse(HttpContext context, HttpRequestMessage request, HttpResponseMessage response, HttpRequestContent requestContent, HttpResponseContent responseContent, CookieCollection cookies) { if (!ApiConfiguration.Instance.EnableHttpZf) { return; } var session = (context.Client as NetClient).Session; if (session == null) { return; } if (!(responseContent is ResponseStringContent) || !context.IsSuccess || response.ContentType.IndexOf("text/html") == -1) { return; } //检测dynamicjs var service = AppContext.ExtensionManager.GlobalKernel.Resolve <IFingerprintService>(); if (!service.IsInitialized) { return; } var m = Regex.Match((responseContent as ResponseStringContent).Result, @"(/otn/HttpZF/[^""]*?)['""]", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (!m.Success) { return; } var jsUrl = m.GetGroupValue(1); var host = new HostContext(session) { ResourceUrl = jsUrl }; #pragma warning disable CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法 Task.Factory.StartNew(() => { if (ProcessFp(host)) { return; } lock (_processingSessions) { if (_processingSessions.Contains(session)) { return; } _processingSessions.Add(session); } do { if (!session.IsLogined) { return; } Thread.Sleep(5000); } while (!ProcessFp(host)); lock (_processingSessions) { _processingSessions.Remove(session); } }); #pragma warning restore CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法 }
public HttpRequestResult(HttpResponseMessage result) { if (result == null) throw new ArgumentNullException("result"); _result = result; _responseContent = new HttpResponseContent(_result.Content); }