public async Task ReadFormAsync_MultipartWithFieldAndFile_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithFieldAndFile); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set <IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get <IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); Assert.Same(formCollection, context.Request.Form); // Content Assert.Equal(1, formCollection.Count); Assert.Equal("Foo", formCollection["description"]); Assert.NotNull(formCollection.Files); Assert.Equal(1, formCollection.Files.Count); var file = formCollection.Files["myfile1"]; Assert.Equal("text/html", file.ContentType); Assert.Equal(@"form-data; name=""myfile1""; filename=""temp.html""", file.ContentDisposition); var body = file.OpenReadStream(); using (var reader = new StreamReader(body)) { Assert.True(body.CanSeek); var content = reader.ReadToEnd(); Assert.Equal("<html><body>Hello World</body></html>", content); } await responseFeature.CompleteAsync(); }
public async Task ReadFormAsync_MultipartWithFieldAndMediumFile_ReturnsParsedFormCollection(bool bufferRequest, int fileSize) { var fileContents = CreateFile(fileSize); var formContent = CreateMultipartWithFormAndFile(fileContents); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set <IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get <IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); Assert.Same(formCollection, context.Request.Form); // Content Assert.Equal(1, formCollection.Count); Assert.Equal("Foo", formCollection["description"]); Assert.NotNull(formCollection.Files); Assert.Equal(1, formCollection.Files.Count); var file = formCollection.Files["myfile1"]; Assert.Equal("text/html", file.ContentType); Assert.Equal(@"form-data; name=""myfile1""; filename=""temp.html""", file.ContentDisposition); using (var body = file.OpenReadStream()) { Assert.True(body.CanSeek); CompareStreams(fileContents, body); } await responseFeature.CompleteAsync(); }
public void SampleTest() { // var testTempData = new Mock<ITempDataDictionary>(); // testTempData // .SetupSet(dictionary => dictionary["myTestItem"] = It.IsAny<object>()) // .Throws<Exception>(); var logger = new Mock <ILogger <HomeController> >(); var context = new DefaultHttpContext(); var controller = new HomeController(logger.Object) { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } }; var formContent = new Dictionary <string, StringValues> { { "kam", "*****@*****.**" } }; var formCollection = new FormCollection(formContent); var formFeature = new FormFeature(formCollection); var queryContent = new Dictionary <string, StringValues> { { "first", "kam" }, { "second", "lagan" } }; var queryFeature = new QueryFeature(new QueryCollection(queryContent)); controller.ControllerContext.HttpContext.Request.Headers["x-name"] = "kam"; controller.ControllerContext.HttpContext.Features.Set <IFormFeature>(formFeature); controller.ControllerContext.HttpContext.Features.Set <IQueryFeature>(queryFeature); var result = controller.Index(); var response = result as ViewResult; Assert.NotNull(response); Assert.Same("Index", response.ViewName); Assert.Same($"kam testing", controller.ViewData["Message"]); }
public async Task ReadFormAsync_0ContentLength_ReturnsEmptyForm() { var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.ContentLength = 0; var formFeature = new FormFeature(context.Request, new FormOptions()); context.Features.Set <IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.Same(FormCollection.Empty, formCollection); }
public async Task ReadFormAsync_MultipartWithInvalidContentDisposition_Throw() { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithInvalidContentDispositionValue); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions()); context.Features.Set <IFormFeature>(formFeature); var exception = await Assert.ThrowsAsync <InvalidDataException>(() => context.Request.ReadFormAsync()); Assert.Equal("Form section has invalid Content-Disposition value: " + InvalidContentDispositionValue, exception.Message); }
private JObject GetFormDataParameter(Stream stream, HttpRequest request) { request.Body = stream; FormFeature formFeature = new FormFeature(request, _formOptions); IFormCollection forms = formFeature.ReadForm(); if (forms == null || forms.Count == 0) { return(null); } JObject json = new JObject(); foreach (var f in forms) { json.Add(f.Key, f.Value.ToString()); } return(json); }
public HttpContext Create(IFeatureCollection featureCollection) { if (featureCollection == null) { throw new ArgumentNullException(nameof(featureCollection)); } var httpContext = new DefaultHttpContext(featureCollection); if (_httpContextAccessor != null) { _httpContextAccessor.HttpContext = httpContext; } var formFeature = new FormFeature(httpContext.Request, _formOptions); featureCollection.Set <IFormFeature>(formFeature); return(httpContext); }
public void GetKey_ReturnsFirstKey1(string[] values) { // Arrange var keyProvider = new FormApiKeyProvider("apikey"); IFormFeature formFeature = new FormFeature(new FormCollection(new Dictionary <string, StringValues>(StringComparer.OrdinalIgnoreCase) { { "apikey", values } })); var context = new DefaultHttpContext(); context.Request.ContentType = "application/x-www-form-urlencoded"; context.Features[typeof(IFormFeature)] = formFeature; // Act var result = keyProvider.GetApiKey(context); // Assert Assert.NotNull(result); Assert.Equal(values[0], result); }
public void SetsRequestFormFeature_WhenFeatureIsPresent_ButFormIsNull() { // Arrange var requestFormLimitsFilter = new RequestFormLimitsFilter(NullLoggerFactory.Instance); requestFormLimitsFilter.FormOptions = new FormOptions(); var authorizationFilterContext = CreateAuthorizationFilterContext( new IFilterMetadata[] { requestFormLimitsFilter }); var oldFormFeature = new FormFeature(authorizationFilterContext.HttpContext.Request); // Set to null explicitly as we want to make sure the filter adds one authorizationFilterContext.HttpContext.Features.Set <IFormFeature>(oldFormFeature); // Act requestFormLimitsFilter.OnAuthorization(authorizationFilterContext); // Assert var actualFormFeature = authorizationFilterContext.HttpContext.Features.Get <IFormFeature>(); Assert.NotSame(oldFormFeature, actualFormFeature); }
public async Task ReadFormAsync_SimpleData_ReplacePipeReader_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes("foo=bar&baz=2"); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; var pipe = new Pipe(); await pipe.Writer.WriteAsync(formContent); pipe.Writer.Complete(); var mockFeature = new MockRequestBodyPipeFeature(); mockFeature.Reader = pipe.Reader; context.Features.Set <IRequestBodyPipeFeature>(mockFeature); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set <IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.Equal("bar", formCollection["foo"]); Assert.Equal("2", formCollection["baz"]); // Cached formFeature = context.Features.Get <IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); // Cleanup await responseFeature.CompleteAsync(); }
public async Task ReadFormAsync_MultipartWithFileAndQuotedBoundaryString_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithSpecialCharacters); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentTypeWithSpecialCharacters; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set <IFormFeature>(formFeature); var formCollection = context.Request.Form; Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get <IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formCollection, formFeature.Form); Assert.Same(formCollection, await context.Request.ReadFormAsync()); // Content Assert.Equal(1, formCollection.Count); Assert.Equal("Foo", formCollection["description"]); Assert.NotNull(formCollection.Files); Assert.Equal(0, formCollection.Files.Count); // Cleanup await responseFeature.CompleteAsync(); }
public async Task GetFormAsync_ReturnsParsedFormCollection() { // Arrange var formContent = Encoding.UTF8.GetBytes("foo=bar&baz=2"); var features = new Mock <IFeatureCollection>(); var request = new Mock <IHttpRequestFeature>(); request.SetupGet(r => r.Body).Returns(new MemoryStream(formContent)); object value = request.Object; features.Setup(f => f.TryGetValue(typeof(IHttpRequestFeature), out value)) .Returns(true); var provider = new FormFeature(features.Object); // Act var formCollection = await provider.GetFormAsync(CancellationToken.None); // Assert Assert.Equal("bar", formCollection["foo"]); Assert.Equal("2", formCollection["baz"]); }
public async Task ReadFormAsync_SimpleData_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes("foo=bar&baz=2"); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set <IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.Equal("bar", formCollection["foo"]); Assert.Equal("2", formCollection["baz"]); Assert.Equal(bufferRequest, context.Request.Body.CanSeek); if (bufferRequest) { Assert.Equal(0, context.Request.Body.Position); } // Cached formFeature = context.Features.Get <IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); // Cleanup await responseFeature.CompleteAsync(); }
public async Task ReadForm_EmptyMultipart_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(EmptyMultipartForm); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set <IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set <IFormFeature>(formFeature); var formCollection = context.Request.Form; Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get <IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formCollection, formFeature.Form); Assert.Same(formCollection, await context.Request.ReadFormAsync()); // Content Assert.Equal(0, formCollection.Count); Assert.NotNull(formCollection.Files); Assert.Equal(0, formCollection.Files.Count); // Cleanup await responseFeature.CompleteAsync(); }
//解析接收的参数 private Dictionary <string, object> CreateDict(string method, out string auth) { auth = ""; Dictionary <string, object> dict = new Dictionary <string, object>(); if (method == "post") { if (context.Request.ContentType == "application/x-www-form-urlencoded") //纯表单 { foreach (KeyValuePair <string, StringValues> kv in context.Request.Form) { if (kv.Key == "__RequestVerificationToken") { continue; } if (!dict.ContainsKey(kv.Key)) { if (auth != "") { auth += "_"; } auth += kv.Key; dict.Add(kv.Key, kv.Value[0]); } } } else if (context.Request.ContentType.Contains("multipart/form-data", StringComparison.OrdinalIgnoreCase)) //带附件的表单 { FormFeature formFeature = new FormFeature(context.Request); IFormCollection iFormCollection = formFeature.ReadForm(); foreach (string key in iFormCollection.Keys) { if (!dict.ContainsKey(key)) { if (auth != "") { auth += "_"; } auth += key; StringValues stringValues = iFormCollection[key]; dict.Add(key, stringValues[0]); } } if (iFormCollection.Files.Count > 0) { IFormFile formFile = iFormCollection.Files[0]; //var target = new System.IO.MemoryStream(); //formFile.CopyTo(target); //byte[] buffer = target.ToArray(); dict.Add(formFile.Name, formFile); if (auth != "") { auth += "_"; } auth += formFile.Name; } } else { var reader = new StreamReader(context.Request.Body); var contentFromBody = reader.ReadToEnd(); if (contentFromBody != "") { dict = JsonConvert.DeserializeObject <Dictionary <string, object> >(contentFromBody); } foreach (KeyValuePair <string, object> kv in dict) { if (kv.Key != _ReqFilter) { if (auth != "") { auth += "_"; } auth += kv.Key; } } } } else if (method == "get") { dict = new Dictionary <string, object>(); foreach (KeyValuePair <string, StringValues> kv in context.Request.Query) { if (!dict.ContainsKey(kv.Key)) { if (auth != "") { auth += "_"; } auth += kv.Key; dict.Add(kv.Key, kv.Value[0]); } } } return(dict); }
public override Task <IFormCollection> ReadFormAsync(CancellationToken cancellationToken) { return(FormFeature.ReadFormAsync(cancellationToken)); }
public StubHttpRequest(HttpContext context) { HttpContext = context; _formFeature = new FormFeature(this); }