public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (context.HttpContext.Request.Headers.ContainsKey("Captcha")) { var configuration = context.HttpContext.RequestServices.GetRequiredService <IConfiguration>(); var configurationSection = configuration.GetSection("Captcha"); HttpClient client = context.HttpContext.RequestServices.GetRequiredService <IHttpClientFactory>().CreateClient(); var captcha = context.HttpContext.Request.Headers["Captcha"]; var uri = $"{configurationSection["Url"]}?secret={configurationSection["Secret"]}&response={captcha}"; var httpResponseMessage = await client.PostAsync(uri, new StringContent("", Encoding.UTF8, "application/json")); await using var stream = await httpResponseMessage.Content.ReadAsStreamAsync(); using var httpRequestStreamReader = new HttpRequestStreamReader(stream, Encoding.UTF8); using var jsonTextReader = new JsonTextReader(httpRequestStreamReader); var deserializeObject = await JObject.LoadAsync(jsonTextReader); if (deserializeObject["success"].Value <bool>()) { await next(); return; } } context.Result = new BadRequestResult(); }
public async Task <ActionResult> RegisterUserPlaintext() { using var reader = new HttpRequestStreamReader(Request.Body, Encoding.UTF8); var user = await reader.ReadToEndAsync(); return(Content(user, "text/plain")); // echo back the user for testing }
public async void CreateUser() { int check; try { using (var streamReader = new HttpRequestStreamReader(Request.Body, Encoding.UTF8)) using (var jsonReader = new JsonTextReader(streamReader)) { var json = await JObject.LoadAsync(jsonReader); var userHolder = json["username"]; var emailHolder = json["email"]; var passwordHolder = json["password"]; User newUser = new User(userHolder.ToString(), emailHolder.ToString(), emailHolder.ToString(), 0); //check = AddUser(newUser); engine.AddUser(newUser); } } catch (Exception e) { // handle exception } }
private async Task <IMessage> CreateMessage(HttpRequest request) { IMessage?requestMessage; if (_bodyDescriptor != null) { if (request.ContentType == null || !request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Request content-type of application/json is required."); } if (!request.Body.CanSeek) { // JsonParser does synchronous reads. In order to avoid blocking on the stream, we asynchronously // read everything into a buffer, and then seek back to the beginning. request.EnableBuffering(); Debug.Assert(request.Body.CanSeek); await request.Body.DrainAsync(CancellationToken.None); request.Body.Seek(0L, SeekOrigin.Begin); } var encoding = RequestEncoding.SelectCharacterEncoding(request); // TODO: Handle unsupported encoding using (var requestReader = new HttpRequestStreamReader(request.Body, encoding)) { if (_bodyDescriptorRepeated) { var containingMessage = ParseRepeatedContent(requestReader); if (_resolvedBodyFieldDescriptors !.Count > 0) { requestMessage = (IMessage)Activator.CreateInstance <TRequest>(); ServiceDescriptorHelpers.RecursiveSetValue(requestMessage, _resolvedBodyFieldDescriptors, containingMessage); } else { requestMessage = containingMessage; } } else { var bodyContent = JsonParser.Default.Parse(requestReader, _bodyDescriptor); if (_bodyFieldDescriptors != null) { requestMessage = (IMessage)Activator.CreateInstance <TRequest>(); ServiceDescriptorHelpers.RecursiveSetValue(requestMessage, _bodyFieldDescriptors, bodyContent); } else { requestMessage = bodyContent; } } }
public static async Task ReadLine_CarriageReturnAndLineFeedAcrossBufferBundaries(Func <HttpRequestStreamReader, Task <string> > action) { // Arrange var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write("123456789\r\nfoo"); writer.Flush(); stream.Position = 0; var reader = new HttpRequestStreamReader(stream, Encoding.UTF8, 10); // Act & Assert var data = await action(reader); Assert.Equal("123456789", data); data = await action(reader); Assert.Equal("foo", data); var eof = await action(reader); Assert.Null(eof); }
public static void NullInputsInConstructor_ExpectArgumentNullException(Stream stream, Encoding encoding, ArrayPool <byte> bytePool, ArrayPool <char> charPool) { Assert.Throws <ArgumentNullException>(() => { var httpRequestStreamReader = new HttpRequestStreamReader(stream, encoding, 1, bytePool, charPool); }); }
public static void NegativeOrZeroBufferSize_ExpectArgumentOutOfRangeException(int size) { Assert.Throws <ArgumentOutOfRangeException>(() => { var httpRequestStreamReader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8, size, ArrayPool <byte> .Shared, ArrayPool <char> .Shared); }); }
private async Task <ApiResponse> GetResponseContentAsync(HttpResponseMessage httpResponseMessage, string fallbackEndpointUrl) { if (httpResponseMessage == null) { throw new ArgumentNullException(nameof(httpResponseMessage)); } if (httpResponseMessage.StatusCode == HttpStatusCode.OK) { var hasStaleContent = HasStaleContent(httpResponseMessage); var continuationToken = httpResponseMessage.Headers.GetContinuationHeader(); var requestUri = httpResponseMessage.RequestMessage?.RequestUri?.AbsoluteUri ?? fallbackEndpointUrl; return(new ApiResponse(httpResponseMessage.Content, hasStaleContent, continuationToken, requestUri)); } Error error = null; // The null-coalescing operator causes tests to fail for NREs, hence the "if" statement. if (httpResponseMessage?.Content != null) { using var streamReader = new HttpRequestStreamReader(await httpResponseMessage.Content.ReadAsStreamAsync(), Encoding.UTF8); using var jsonReader = new JsonTextReader(streamReader); error = Serializer.Deserialize <Error>(jsonReader); } if (error != null) { return(new ApiResponse(httpResponseMessage.Content, false, null, null, error)); } throw new DeliveryException(httpResponseMessage); }
public async void CreateTask() { int check; try { using (var streamReader = new HttpRequestStreamReader(Request.Body, Encoding.UTF8)) using (var jsonReader = new JsonTextReader(streamReader)) { var json = await JObject.LoadAsync(jsonReader); var projectNameHolder = json["projectName"]; var escalationValHolder = json["escalationValue"]; var workerNameHolder = json["assignedWorker"]; var taskNameHolder = json["taskName"]; var taskDescriptionHolder = json["description"]; Task newTask = new Task(projectNameHolder.ToString(), int.Parse((escalationValHolder.ToString())), workerNameHolder.ToString(), taskNameHolder.ToString(), taskDescriptionHolder.ToString()); check = engine.AddTask(newTask); } } catch (Exception e) { // handle exception } }
public async Task <ActionResult> UploadCoverImage(string artistId) { try { PikchaUser pikchaUser = await _userManager.GetUserAsync(this.User); if (pikchaUser == null) { return(StatusCode(StatusCodes.Status404NotFound, PikchaMessages.MESS_Status404_UserNotFound)); } /* bool isArtist = await _userManager.IsInRoleAsync(pikchaUser, PikchaConstants.PIKCHA_ROLES_ARTIST_NAME); * if(! isArtist) * { * return StatusCode(StatusCodes.Status404NotFound, PikchaMessages.MESS_Status404_ArtistNotFound); * } */ using (var streamReader = new HttpRequestStreamReader(Request.Body, Encoding.UTF8)) using (var jsonReader = new JsonTextReader(streamReader)) { var json = await JObject.LoadAsync(jsonReader); string coverContent = (string)json["coverContent"]; if (coverContent.Contains(',')) { coverContent = coverContent.Split(",")[1]; } //string tmp = (string)json["signatureContent"]["data"]; ImageProcessingManager manager = new ImageProcessingManager(_hostingEnvironment, _configuration); // = ""; string filePath = string.Empty; manager.ProcessCoverImage(coverContent, ref filePath); // get the PikchaUser from ClaimsPrincipal {{this.User}} and save the file location if (!string.IsNullOrEmpty(filePath)) { pikchaUser.Cover = filePath; await _pikchDbContext.SaveChangesAsync(); //var pikchaUserQuery = _pikchDbContext.PikchaUsers.Include("Images.Views").Include("Following").Include("Following.PikchaUser").Include("Following.Artist").Where(u => u.Id == artistId); // var userDTO = await _mapper.ProjectTo<ArtistDTO>(pikchaUserQuery).FirstAsync(); var pikchaUserDb = await _pikchDbContext.PikchaUsers.Include("Images.Views").Include("Following.Artist").Include("Followers.PikchaUser").FirstAsync(u => u.Id == pikchaUser.Id); var userDTO = _mapper.Map <ArtistDTO>(pikchaUserDb); return(ReturnOkOrErrorStatus(userDTO)); } else { Log.Error(" Profile, UploadCoverImage, userId ={userId}, filePath={filePath}", artistId, filePath); return(StatusCode(StatusCodes.Status500InternalServerError, PikchaMessages.MESS_Status500InternalServerError)); } } } catch (Exception ex) { Log.Error(ex, " Profile, UploadCoverImage, userId ={userId}", artistId); return(StatusCode(StatusCodes.Status500InternalServerError, PikchaMessages.MESS_Status404ImageNotFound)); } }
public static async Task StreamDisposed_ExpectObjectDisposedExceptionAsync(Func <HttpRequestStreamReader, Task> action) { var httpRequestStreamReader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8, 10, ArrayPool <byte> .Shared, ArrayPool <char> .Shared); httpRequestStreamReader.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(() => action(httpRequestStreamReader)); }
internal object ReadRequest(HttpContext context, CrpcVersionRegistration version) { if (version.RequestType == null) { return(null); } if ((context.Request.ContentLength ?? 0) == 0) { throw new CrpcException("invalid_body"); } using (var sr = new HttpRequestStreamReader(context.Request.Body, Encoding.UTF8)) using (var jtr = new JsonTextReader(sr)) using (var jsv = new JSchemaValidatingReader(jtr)) { var validationErrors = new List <CrpcException>(); jsv.Schema = version.Schema; jsv.ValidationEventHandler += (o, a) => { validationErrors.Add(new CrpcException("validation_error", new Dictionary <string, object> { { "message", a.ValidationError.Message }, { "value", a.ValidationError.Value }, { "path", a.ValidationError.Path }, { "location", $"line {a.ValidationError.LineNumber}, position {a.ValidationError.LinePosition}" }, })); }; object deserialized = null; try { deserialized = _jsonDeserializeMethod .MakeGenericMethod(version.RequestType) .Invoke(_jsonSerializer, new object[] { jsv }); } catch (TargetInvocationException ex) { var innerEx = ex.InnerException; // If the exception isn't a serialization exception, throw if (!(innerEx is JsonSerializationException)) { throw innerEx; } } // Handle errors if (validationErrors.Count() > 0) { throw new CrpcException(CrpcCodes.ValidationFailed, null, validationErrors.AsEnumerable()); } return(deserialized); } }
public static async Task ReadToEndAsync() { // Arrange var reader = new HttpRequestStreamReader(GetLargeStream(), Encoding.UTF8); var result = await reader.ReadToEndAsync(); Assert.Equal(5000, result.Length); }
public static void StreamCannotRead_ExpectArgumentException() { var mockStream = new Mock <Stream>(); mockStream.Setup(m => m.CanRead).Returns(false); Assert.Throws <ArgumentException>(() => { var httpRequestStreamReader = new HttpRequestStreamReader(mockStream.Object, Encoding.UTF8, 1, ArrayPool <byte> .Shared, ArrayPool <char> .Shared); }); }
public async Task <ActionResult> UploadAvatarImage(string userId) { try { using (var streamReader = new HttpRequestStreamReader(Request.Body, Encoding.UTF8)) using (var jsonReader = new JsonTextReader(streamReader)) { var json = await JObject.LoadAsync(jsonReader); string avatarContent = (string)json["avatarContent"]; if (avatarContent.Contains(',')) { avatarContent = avatarContent.Split(",")[1]; } //string tmp = (string)json["signatureContent"]["data"]; ImageProcessingManager manager = new ImageProcessingManager(_hostingEnvironment, _configuration); // = ""; string filePath = string.Empty; manager.ProcessAvatarFile(avatarContent, ref filePath); // get the PikchaUser from ClaimsPrincipal {{this.User}} and save the file location PikchaUser pikchaUser = await _userManager.GetUserAsync(this.User); if (pikchaUser == null) { return(StatusCode(StatusCodes.Status404NotFound, PikchaMessages.MESS_Status404_UserNotFound)); } if (!string.IsNullOrEmpty(filePath)) { pikchaUser.Avatar = filePath; await _pikchDbContext.SaveChangesAsync(); var lgUSer = _mapper.Map <AuthenticatedUserDTO>(pikchaUser); var roles = await _userManager.GetRolesAsync(pikchaUser); if (roles != null) { lgUSer.Roles = roles.ToList(); } return(Ok(lgUSer)); } else { Log.Error(" Profile, UploadAvatarImage, userId ={userId}, filePath={filePath}", userId, filePath); return(StatusCode(StatusCodes.Status500InternalServerError, PikchaMessages.MESS_Status500InternalServerError)); } } } catch (Exception ex) { Log.Error(ex, " Profile, UploadAvatarImage, userId ={userId}", userId); return(StatusCode(StatusCodes.Status500InternalServerError, PikchaMessages.MESS_Status404ImageNotFound)); } }
public ActionResult <ResolvedURL> Submit() { using (var streamReader = new HttpRequestStreamReader(Request.Body, System.Text.Encoding.UTF8)) { // deserialize JSON URLContainer urlObj = JsonConvert.DeserializeObject <URLContainer>(streamReader.ReadToEnd()); ResolvedURL randomUrl = LinkGenerator.AddURL(urlObj.url); return(randomUrl); } }
public static async Task ReadLine_EOF(Func <HttpRequestStreamReader, Task <string> > action) { // Arrange var stream = new MemoryStream(); var reader = new HttpRequestStreamReader(stream, Encoding.UTF8); // Act & Assert var eof = await action(reader); Assert.Null(eof); }
public static void StreamDisposed_ExpectedObjectDisposedException(Action <HttpRequestStreamReader> action) { var httpRequestStreamReader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8, 10, ArrayPool <byte> .Shared, ArrayPool <char> .Shared); httpRequestStreamReader.Dispose(); Assert.Throws <ObjectDisposedException>(() => { action(httpRequestStreamReader); }); }
public static async Task StreamDisposed_ExpectObjectDisposedExceptionAsync() { var httpRequestStreamReader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8, 10, ArrayPool <byte> .Shared, ArrayPool <char> .Shared); httpRequestStreamReader.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(() => { return(httpRequestStreamReader.ReadAsync(new char[10], 0, 1)); }); }
public static Order Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = "order")] HttpRequest req, TraceWriter log) { log.Info("SaveAnOrder: C# HTTP trigger function processed a request."); var bodyString = new HttpRequestStreamReader(req.Body, Encoding.UTF8).ReadToEnd(); var postedOrder = JsonConvert.DeserializeObject <PostOrder>(bodyString); log.Info(bodyString); return(Order.From(postedOrder)); }
public virtual async Task HandleUpdateEntityAsync(string modelId, string entityContainer, string keyStr, CancellationToken ct = default) { using (var reader = new HttpRequestStreamReader(HttpContext.Request.Body, Encoding.UTF8)) using (var jsReader = new JsonTextReader(reader)) { var props = await JObject.LoadAsync(jsReader); var result = await Manager.UpdateEntityAsync(modelId, entityContainer, keyStr, props, ct); await WriteOkJsonResponseAsync(HttpContext, async (jsonWriter, cancellationToken) => { await WriteUpdateEntityResponseAsync(jsonWriter, result, cancellationToken); }, ct); } }
public virtual async Task HandleGetEntitiesAsync(string modelId, string entityContainer, CancellationToken ct = default) { int?offset = null; int?fetch = null; bool isLookup = false; IEnumerable <EasyFilter> filters = null; bool needTotal = false; JObject requestParams; using (var requestReader = new HttpRequestStreamReader(HttpContext.Request.Body, Encoding.UTF8)) using (var jsonReader = new JsonTextReader(requestReader)) { requestParams = await JObject.LoadAsync(jsonReader, ct); } if (requestParams.TryGetValue("offset", out var value)) { offset = value.ToObject <int?>(); } if (requestParams.TryGetValue("limit", out value)) { fetch = value.ToObject <int?>(); } if (requestParams.TryGetValue("needTotal", out value)) { needTotal = value.ToObject <bool>(); } if (requestParams.TryGetValue("lookup", out value)) { isLookup = value.ToObject <bool>(); } if (requestParams.TryGetValue("filters", out value) && value.HasValues) { filters = await GetFiltersAsync(modelId, (JArray)value, ct); } long?total = null; if (needTotal) { total = await Manager.GetTotalEntitiesAsync(modelId, entityContainer, filters, isLookup, ct); } var result = await Manager.GetEntitiesAsync(modelId, entityContainer, filters, isLookup, offset, fetch); await WriteOkJsonResponseAsync(HttpContext, async (jsonWriter, cancellationToken) => { await WriteGetEntitiesResponseAsync(jsonWriter, result, total, cancellationToken); }, ct); }
public static void EmptyStream() { // Arrange var reader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8); var buffer = new char[10]; // Act var read = reader.Read(buffer, 0, 1); // Assert Assert.Equal(0, read); }
public virtual async Task HandleCreateEntityAsync(string modelId, string entityContainer) { using (var reader = new HttpRequestStreamReader(HttpContext.Request.Body, Encoding.UTF8)) using (var jsReader = new JsonTextReader(reader)) { var props = await JObject.LoadAsync(jsReader); var result = await Manager.CreateEntityAsync(modelId, entityContainer, props); await WriteOkJsonResponseAsync(HttpContext, async jsonWriter => { await WriteCreateEntityResponseAsync(jsonWriter, result); }); } }
/// <summary> /// Deserializes an object from XML or JSON /// </summary> /// <returns>Deserialized object</returns> public static object Deserialize(Type type, HttpRequest contextRequest) { string contentType = contextRequest.ContentType; if (string.IsNullOrWhiteSpace(contentType)) { contentType = ApiActionResult.JSON_CONTENT_TYPE; } else if (contentType.ToLower().Contains(ApiActionResult.JSON_CONTENT_TYPE)) { contentType = ApiActionResult.JSON_CONTENT_TYPE; } else if (contentType.ToLower().Contains(ApiActionResult.XML_CONTENT_TYPE)) { contentType = ApiActionResult.XML_CONTENT_TYPE; } else { contentType = ApiActionResult.JSON_CONTENT_TYPE; } // The InputStream was already parsed by the controller let's reset the inputstream position to 0 //contextRequest.Body.Position = 0; if (contentType == ApiActionResult.XML_CONTENT_TYPE) { XmlSerializer serializer = new XmlSerializer(type); return(serializer.Deserialize(contextRequest.Body)); } else { using (TextReader textReader = new HttpRequestStreamReader(contextRequest.Body, Encoding.UTF8)) using (JsonReader jsonReader = new JsonTextReader(textReader)) { JsonSerializer serializer = new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new ApiActionResult.CustomDateTimeFormatResolver(), DateTimeZoneHandling = DateTimeZoneHandling.Local }; object o = serializer.Deserialize(jsonReader, type); if (o == null) { // If null, then get a empty instance o = Activator.CreateInstance(type); } return(o); } } }
public async Task <IActionResult> BigContentManualGood() { var streamReader = new HttpRequestStreamReader(Request.Body, Encoding.UTF8); var jsonReader = new JsonTextReader(streamReader); var serializer = new JsonSerializer(); // This asynchronously reads the entire payload into a JObject then turns it into the real object. var obj = await JToken.ReadFromAsync(jsonReader); var rootobject = obj.ToObject <PokemonData>(serializer); return(Accepted()); }
public static async Task ReadToEndAsync_Reads_Asynchronously() { // Arrange var stream = new AsyncOnlyStreamWrapper(GetLargeStream()); var reader = new HttpRequestStreamReader(stream, Encoding.UTF8); var streamReader = new StreamReader(GetLargeStream()); string expected = await streamReader.ReadToEndAsync(); // Act var actual = await reader.ReadToEndAsync(); // Assert Assert.Equal(expected, actual); }
public async Task <ActionResult> Post([FromForm(Name = "file")] IFormFile file) { var userId = Guid.Parse(this.User.Claims.Single(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").Value); var stream = file.OpenReadStream(); var httpRequestStreamReader = new HttpRequestStreamReader(stream, Encoding.Default); var xmlTextReader = new XmlTextReader(httpRequestStreamReader); var xs = new XmlSerializer(typeof(Opml)); var opml = (Opml)xs.Deserialize(xmlTextReader); var command = new ImportSubscriptionsRequest(userId, opml); await this.mediator.Send(command); return(this.Ok()); }
public static async Task <JObject> ToJObject(this Stream stream) { try { using (var streamReader = new HttpRequestStreamReader(stream, Encoding.UTF8)) { using (var jsonReader = new JsonTextReader(streamReader)) { return(await JObject.LoadAsync(jsonReader)); } } } catch { return(null); } }
public static async Task ReadLine_NewLineOnly(Func <HttpRequestStreamReader, Task <string> > action) { // Arrange var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write("\r\n"); writer.Flush(); stream.Position = 0; var reader = new HttpRequestStreamReader(stream, Encoding.UTF8); // Act & Assert var empty = await action(reader); Assert.Equal(string.Empty, empty); }