/// <summary>
        /// The WriteJsonAsync.
        /// </summary>
        /// <param name="response">The response<see cref="Microsoft.AspNetCore.Http.HttpResponse"/>.</param>
        /// <param name="json">The json<see cref="string"/>.</param>
        /// <param name="contentType">The contentType<see cref="string"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public static async Task WriteJsonAsync(this Microsoft.AspNetCore.Http.HttpResponse response, string json, string contentType = null)
        {
            response.ContentType = (contentType ?? "application/json; charset=UTF-8");
            await response.WriteAsync(json);

            await response.Body.FlushAsync();
        }
예제 #2
0
 public Response(IRequestContext requestContext, HttpContext context)
 {
     this.res      = context.Response;
     this.baseBody = context.Response.Body;
     this.Context  = requestContext;
     this.Headers  = new Headers(context.Response.Headers);
 }
예제 #3
0
        static public void AssignPlayerCookies(CreateGameModel model, Microsoft.AspNetCore.Http.HttpResponse Response)
        {
            CookieOptions cookie = new CookieOptions();

            cookie.Expires = DateTime.Now.AddHours(1);
            Response.Cookies.Append("gameid", model.GameId.ToString(), cookie);
        }
        private async Task <string> FormatResponse(Microsoft.AspNetCore.Http.HttpResponse response)
        {
            var text = string.Empty;

            if (response.StatusCode == (int)HttpStatusCode.OK)
            {
                response.Body.Seek(0, SeekOrigin.Begin);
                text = await new StreamReader(response.Body).ReadToEndAsync();
                response.Body.Seek(0, SeekOrigin.Begin);
            }
            else if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
            {
                text = "Not Authorized";
            }
            else if (response.StatusCode == (int)HttpStatusCode.Forbidden)
            {
                if (response.HttpContext.User.Identity.IsAuthenticated)
                {
                    text = "Authenticated but Forbidden";
                }
                else
                {
                    text = "Not Authorized";
                }
            }

            return($"Response {text}");
        }
예제 #5
0
        /// <summary>
        /// 覆盖 JsonResult 的方法;
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            var data = this.GetJsonResultValue();

            if (data != null)
            {
                IsoDateTimeConverter timeConvert = new IsoDateTimeConverter();
                timeConvert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                string content = "";
                if (data is SerializeToJson)
                {
                    content = ((SerializeToJson)data).SerializeToJson();
                }
                else
                {
                    content = JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.None, timeConvert);
                }
                response.Write(content);
            }
        }
예제 #6
0
        public static void WriteJson <T>(this Microsoft.AspNetCore.Http.HttpResponse response, T obj, string contentType = null)
        {
            response.ContentType = contentType ?? "application/json";

            var json = JsonSerializer.Serialize(obj, obj.GetType());

            response.WriteAsync(json, Encoding.UTF8);
        }
        public ExtractedResponse(HttpResponse response)
        {
            using (var reader = new StreamReader(response.Body))
            {
                Body = reader.ReadToEnd();
            }

            StatusCode = (HttpStatusCode)response.StatusCode;
        }
예제 #8
0
 public static void ApagaCookie(Microsoft.AspNetCore.Http.HttpResponse response, Microsoft.AspNetCore.Http.HttpRequest request)
 {
     foreach (var cookie in request.Cookies)
     {
         try
         {
             if (cookie.Key.ToUpper().StartsWith("GLOBAL_"))
             {
                 response.Cookies.Delete(cookie.Key);
             }
         }
         catch (Exception ex)
         {
             string strMessage = ex.Message;
         }
     }
 }
예제 #9
0
        public override void ExecuteResult(Microsoft.AspNetCore.Mvc.ActionContext context)
        {
            Microsoft.AspNetCore.Http.HttpResponse response = context.HttpContext.Response;

            //if (this.m_data == null)
            //{
            //    response.StatusCode = StatusCodes.Status500InternalServerError;
            //    return;
            //}

            byte[] data = this.m_enc.GetBytes(this.m_text);

            response.StatusCode    = StatusCodes.Status200OK;
            response.ContentLength = data.Length;
            response.ContentType   = this.m_MimeType + "; charset=" + this.Encoding.WebName;
            response.Body.Write(data, 0, data.Length);
        }
        public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            if (httpResponse == null)
            {
                throw new ArgumentNullException(nameof(httpResponse));
            }

            if (bot == null)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            if (_options.ValidateIncomingZoomRequests &&
                httpRequest.Headers.TryGetValue("HeaderAuthorization", out StringValues headerAuthorization) &&
                headerAuthorization.FirstOrDefault() != _options.VerificationToken)
            {
                throw new AuthenticationException("Failed to validate incoming request. Mismatched verification token.");
            }

            string body;

            using (var sr = new StreamReader(httpRequest.Body))
            {
                body = await sr.ReadToEndAsync();
            }

            var zoomRequest = JsonConvert.DeserializeObject <ZoomRequest>(body, JsonSerializerSettings);

            var activity = RequestToActivity(zoomRequest);

            using (var context = new TurnContext(this, activity))
            {
                await RunPipelineAsync(context, bot.OnTurnAsync, cancellationToken).ConfigureAwait(false);

                var statusCode = Convert.ToInt32(context.TurnState.Get <string>("httpStatus"), CultureInfo.InvariantCulture);
                var text       = context.TurnState.Get <object>("httpBody") != null?context.TurnState.Get <object>("httpBody").ToString() : string.Empty;

                await WriteAsync(httpResponse, statusCode, text, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
            }
        }
예제 #11
0
        public override async Task <string> Handle(HttpRequest request, HttpResponse response)
        {
            try {
                string url = HttpUtility.UrlDecode(request.QueryString.Value);
                if (request.Method == "POST")
                {
                    using (var readStream = new StreamReader(request.Body, Encoding.UTF8)) {
                        url = readStream.ReadToEnd();
                    }
                }

                if (url.StartsWith("s=B"))
                {
                    url = url.Substring(3);

                    string contentId = FileList.GetContentId(url);
                    return(await GetFileList(FileList.GetFileList(contentId, "content_id"), contentId, "content_id"));
                }
                else if (url.StartsWith("torrenturl="))
                {
                    url = url.Substring(11);
                    url = HttpUtility.UrlDecode(url);
                    if (url.StartsWith("torrent://"))
                    {
                        url = url.Substring(10);
                    }

                    var data = await HTTPUtility.GetBytesRequestAsync(url);

                    string contentId = FileList.GetContentId(data);
                    return(await GetFileList(FileList.GetFileList(contentId, "content_id"), contentId, "content_id"));
                }
                else if (url.StartsWith("magnet="))
                {
                    url = url.Substring(7);

                    return(await GetFileList(FileList.GetFileList(url, "magnet"), url, "magnet"));
                }

                return(string.Empty);
            } catch (Exception exception) {
                Log.LogError(exception);
                return(exception.Message);
            }
        }
예제 #12
0
        public override void ExecuteResult(Microsoft.AspNetCore.Mvc.ActionContext context)
        {
            Microsoft.AspNetCore.Http.HttpResponse response = context.HttpContext.Response;

            //if (this.m_data == null)
            //{
            //    response.StatusCode = StatusCodes.Status500InternalServerError;
            //    return;
            //}

            response.StatusCode  = StatusCodes.Status200OK;
            response.ContentType = "application/javascript; charset=utf-8";

            Services.JsonSerializer ser = (Services.JsonSerializer)context.HttpContext
                                          .RequestServices.GetService(typeof(Services.JsonSerializer));
            ser.SerializeJsonp(context.HttpContext.Response.Body, "callback"
                               , this.m_data, this.m_prettyPrint);
        }
예제 #13
0
        public static void CarregaCookie(Microsoft.AspNetCore.Http.HttpResponse response, ISession session)
        {
            CookieOptions option = new CookieOptions();

            option.Expires = DateTime.Now.AddDays(1);

            foreach (string key in session.Keys)
            {
                try
                {
                    if (key.ToUpper().StartsWith("GLOBAL_"))
                    {
                        response.Cookies.Append(key, session.GetString(key), option);
                    }
                }
                catch (Exception ex)
                {
                    string strMessage = ex.Message;
                }
            }
        }
예제 #14
0
        public async Task LunchPaymentPage(HttpContext httpContext, string authorizationUrl)
        {
            Microsoft.AspNetCore.Http.HttpResponse response = httpContext.Response;
            response.Clear();

            StringBuilder form = new StringBuilder();

            form.Append("<html>");
            form.AppendFormat("<body onload='document.forms[0].submit()'>");
            form.AppendFormat("<form action='{0}' method='post'>", authorizationUrl);
            form.Append("</form>");
            form.Append("</body>");
            form.Append("</html>");

            HasLunchedPaymentPage = true;
            await response.WriteAsync(form.ToString());



            //response.Write(form.ToString());
            //response.End();
        }
예제 #15
0
        public async Task WriteFileByteStreamToBody(Microsoft.AspNetCore.Http.HttpResponse Response, Guid id)
        {
            var _data = await ge_DbContext.ge_data
                        .Include(d => d.project)
                        .SingleOrDefaultAsync(m => m.Id == id);

            Response.StatusCode = 200;
            Response.Headers.Add(HeaderNames.ContentDisposition, $"attachment; filename=\"{Path.GetFileName( _data.filename )}\"");
            Response.Headers.Add(HeaderNames.ContentType, _data.filetype);

            string   data_field = _data.GetContentFieldName();
            Encoding encode     = _data.GetEncoding();

            using (var connection = _context.Database.GetDbConnection()) {
                DbCommand command = connection.CreateCommand();
                command.CommandText    = $"SELECT {data_field} FROM ge_data where id='{id}'";
                command.CommandTimeout = 0;
                connection.Open();
                using (var dataReader = command.ExecuteReader()) {
                    dataReader.Read();
                    using (var inputStream = dataReader.GetCharStream(data_field, encode)) {
                        using (var outputStream = Response.Body) {;
                                                                  const int bufferSize = 8192;
                                                                  var       buffer     = new byte[bufferSize];
                                                                  while (true)
                                                                  {
                                                                      var bytesRead = await inputStream.ReadAsync(buffer, 0, bufferSize);

                                                                      if (bytesRead == 0)
                                                                      {
                                                                          break;
                                                                      }
                                                                      await outputStream.WriteAsync(buffer, 0, bytesRead);
                                                                  }
                                                                  await outputStream.FlushAsync(); }
                    }
                }
            }
        }
        public static async Task WriteAsync(HttpResponse response, int code, string text, Encoding encoding, CancellationToken cancellationToken)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }

            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            response.ContentType = "text/plain";
            response.StatusCode  = code;

            var data = encoding.GetBytes(text);

            await response.Body.WriteAsync(data, 0, data.Length, cancellationToken).ConfigureAwait(false);
        }
예제 #17
0
 public DCRadiumResponse(Microsoft.AspNetCore.Http.HttpResponse res)
 {
     this.res = res;
 }
예제 #18
0
        /// <summary>
        /// 写给定字符串到 响应端;
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static void Write(this HttpResponseBase response, string content)
        {
            var contents = System.Text.Encoding.UTF8.GetBytes(content);

            response.Body.Write(contents, 0, contents.Length);
        }
예제 #19
0
        public async Task <ResponseStructure> UpdatePassword(HttpRequest httpRequest, Microsoft.AspNetCore.Http.HttpResponse response, int userId)
        {
            try
            {
                UserModel userModel = await this.GetById(userId);

                if (userModel == null)
                {
                    return(ResponseModel.Error("Your login token has expired.", new { EXPIREDTOKEN = true }));
                }
                var           data = httpRequest.Headers["PasswordUpdate"];
                var           dec  = Barayand.Common.Services.CryptoJsService.DecryptStringAES(data);
                RegisterModel rm   = JsonConvert.DeserializeObject <RegisterModel>(dec);
                if (!Barayand.Common.Services.CryptoJsService.verifyPassword(userModel.U_Password, rm.CurrentPassword))
                {
                    return(ResponseModel.Error("Current password was incorrect."));
                }
                if (rm.ConfirmPassword != rm.Password)
                {
                    return(ResponseModel.Error("Password and confirm password does not match."));
                }
                userModel.U_Password = Barayand.Common.Services.CryptoJsService.HashPassword(rm.Password);
                response.Cookies.Delete("ValhallaUser");
                return(await this.Update(userModel));
            }
            catch (Exception ex)
            {
                return(ResponseModel.ServerInternalError(data: ex));
            }
        }
예제 #20
0
 public HttpResponse(Microsoft.AspNetCore.Http.HttpResponse httpResponse, ILogger logger)
 {
     _httpResponse = httpResponse;
     _logger       = logger;
 }
예제 #21
0
 protected abstract bool ShouldLog(Microsoft.AspNetCore.Http.HttpRequest request, Microsoft.AspNetCore.Http.HttpResponse response);
예제 #22
0
 public HttpResponse(Microsoft.AspNetCore.Http.HttpResponse httpResponse, ISerializer serializer, ILogger logger)
 {
     _httpResponse = httpResponse;
     _serializer   = serializer;
     _logger       = logger;
 }
예제 #23
0
 public static Task WriteJson <T>(this Microsoft.AspNetCore.Http.HttpResponse response, T obj)
 {
     response.ContentType = "application/json";
     return(response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(obj)));
 } // End Function MapAny
예제 #24
0
 public static void Remove(this Microsoft.AspNetCore.Http.HttpResponse HttpResponse, string key)
 {
     HttpResponse.Cookies.Delete(key);
 }
예제 #25
0
 public NetCoreCookies(Microsoft.AspNetCore.Http.HttpResponse response)
 {
     this.response = response;
 }
예제 #26
0
 public HttpResponse(HttpContext context)
 {
     this.res     = context.Response;
     this.Headers = new Headers(new HttpHeaders(context.Response.Headers));
 }
예제 #27
0
 public static bool IsSuccessfulResponse(this HttpResponse httpResponse)
 {
     return(httpResponse.StatusCode >= (int)HttpStatusCode.OK && httpResponse.StatusCode <= 299);
 }