/// <inheritdoc />
        public async Task<ModelBindingResult> BindModelAsync([NotNull] ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(IFormCollection) &&
                bindingContext.ModelType != typeof(FormCollection))
            {
                return null;
            }

            object model = null;
            var request = bindingContext.OperationBindingContext.HttpContext.Request;
            if (request.HasFormContentType)
            {
                var form = await request.ReadFormAsync();
                if (bindingContext.ModelType.GetTypeInfo().IsAssignableFrom(form.GetType().GetTypeInfo()))
                {
                    model = form;
                }
                else
                {
                    var formValuesLookup = form.ToDictionary(p => p.Key,
                                                             p => p.Value);
                    model = new FormCollection(formValuesLookup, form.Files);
                }
            }
            else
            {
                model = new FormCollection(new Dictionary<string, string[]>());
            }

            return new ModelBindingResult(model, bindingContext.ModelName, isModelSet: true);
        }
        public async Task FormCollectionModelBinder_ValidType_BindSuccessful()
        {
            // Arrange
            var formCollection = new FormCollection(new Dictionary<string, StringValues>
            {
                { "field1", "value1" },
                { "field2", "value2" }
            });
            var httpContext = GetMockHttpContext(formCollection);
            var bindingContext = GetBindingContext(typeof(IFormCollection), httpContext);
            var binder = new FormCollectionModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotEqual(ModelBindingResult.NoResult, result);
            Assert.True(result.IsModelSet);

            var entry = bindingContext.ValidationState[result.Model];
            Assert.True(entry.SuppressValidation);
            Assert.Null(entry.Key);
            Assert.Null(entry.Metadata);

            var form = Assert.IsAssignableFrom<IFormCollection>(result.Model);
            Assert.Equal(2, form.Count);
            Assert.Equal("value1", form["field1"]);
            Assert.Equal("value2", form["field2"]);
        }
        public async Task FormCollectionModelBinder_ValidType_BindSuccessful()
        {
            // Arrange
            var formCollection = new FormCollection(new Dictionary<string, string[]>
            {
                { "field1", new string[] { "value1" } },
                { "field2", new string[] { "value2" } }
            });
            var httpContext = GetMockHttpContext(formCollection);
            var bindingContext = GetBindingContext(typeof(FormCollection), httpContext);
            var binder = new FormCollectionModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotNull(result);
            Assert.True(result.IsModelSet);
            Assert.NotNull(result.ValidationNode);
            Assert.True(result.ValidationNode.SuppressValidation);

            var form = Assert.IsAssignableFrom<IFormCollection>(result.Model);
            Assert.Equal(2, form.Count);
            Assert.Equal("value1", form["field1"]);
            Assert.Equal("value2", form["field2"]);
        }
        public async Task<IActionResult> AddEvent(FormCollection form)
        {

            bool allDay;
            Boolean.TryParse(form["allDay"], out allDay);
            string name = form["Event Name"];
            string start = form["StartDateTime"];
            string end = form["EndDateTime"];

            var user = await GetCurrentUserAsync();

            if (allDay)
            {
                _db.Events.Add(new CalendarEvent(name, start)
                {
                    UserId = user.Id
                });

            }
            else
            {
                _db.Events.Add(new CalendarEvent(name, start, end)
                {
                    UserId = user.Id
                });
            }
            await _db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage();

            if (request.RequestUri.AbsoluteUri.StartsWith("https://login.live.com/oauth20_token.srf"))
            {
                var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync()));
                if (formData["grant_type"] == "authorization_code")
                {
                    if (formData["code"] == "ValidCode")
                    {
                        if (formData["redirect_uri"] != null && formData["redirect_uri"].EndsWith("signin-microsoft") &&
                           formData["client_id"] == "[ClientId]" && formData["client_secret"] == "[ClientSecret]")
                        {
                            response.Content = new StringContent("{\"token_type\":\"bearer\",\"expires_in\":3600,\"scope\":\"wl.basic\",\"access_token\":\"ValidAccessToken\",\"refresh_token\":\"ValidRefreshToken\",\"authentication_token\":\"ValidAuthenticationToken\"}");
                        }
                    }
                }
            }
            else if (request.RequestUri.AbsoluteUri.StartsWith("https://apis.live.net/v5.0/me"))
            {
                if (request.Headers.Authorization.Parameter == "ValidAccessToken")
                {
                    response.Content = new StringContent("{\r   \"id\": \"fccf9a24999f4f4f\", \r   \"name\": \"AspnetvnextTest AspnetvnextTest\", \r   \"first_name\": \"AspnetvnextTest\", \r   \"last_name\": \"AspnetvnextTest\", \r   \"link\": \"https://profile.live.com/\", \r   \"gender\": null, \r   \"locale\": \"en_US\", \r   \"updated_time\": \"2013-08-27T22:18:14+0000\"\r}");
                }
                else
                {
                    response.Content = new StringContent("{\r   \"error\": {\r      \"code\": \"request_token_invalid\", \r      \"message\": \"The access token isn't valid.\"\r   }\r}", Encoding.UTF8, "text/javascript");
                }
            }

            return response;
        }
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage();

            if (request.RequestUri.AbsoluteUri.StartsWith("https://accounts.google.com/o/oauth2/token"))
            {
                var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync()));
                if (formData["grant_type"] == "authorization_code")
                {
                    if (formData["code"] == "ValidCode")
                    {
                        if (formData["redirect_uri"].Count > 0 && ((string)formData["redirect_uri"]).EndsWith("signin-google") &&
                           formData["client_id"] == "[ClientId]" && formData["client_secret"] == "[ClientSecret]")
                        {
                            response.Content = new StringContent("{\"access_token\":\"ValidAccessToken\",\"refresh_token\":\"ValidRefreshToken\",\"token_type\":\"Bearer\",\"expires_in\":\"1200\",\"id_token\":\"Token\"}", Encoding.UTF8, "application/json");
                        }
                    }
                }
            }
            else if (request.RequestUri.AbsoluteUri.StartsWith("https://www.googleapis.com/plus/v1/people/me"))
            {
                if (request.Headers.Authorization.Parameter == "ValidAccessToken")
                {
                    response.Content = new StringContent("{ \"kind\": \"plus#person\",\n \"etag\": \"\\\"YFr-hUROXQN7IOa3dUHg9dQ8eq0/2hY18HdHEP8NLykSTVEiAhkKsBE\\\"\",\n \"gender\": \"male\",\n \"emails\": [\n  {\n   \"value\": \"[email protected]\",\n   \"type\": \"account\"\n  }\n ],\n \"objectType\": \"person\",\n \"id\": \"106790274378320830963\",\n \"displayName\": \"AspnetvnextTest AspnetvnextTest\",\n \"name\": {\n  \"familyName\": \"AspnetvnextTest\",\n  \"givenName\": \"FirstName\"\n },\n \"url\": \"https://plus.google.com/106790274378320830963\",\n \"image\": {\n  \"url\": \"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50\"\n },\n \"isPlusUser\": true,\n \"language\": \"en\",\n \"circledByCount\": 0,\n \"verified\": false\n}\n", Encoding.UTF8, "application/json");
                }
                else
                {
                    response.Content = new StringContent("{\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190}}");
                }
            }

            return response;
        }
 protected override IEnumerableValueProvider GetEnumerableValueProvider(
     BindingSource bindingSource,
     Dictionary<string, StringValues> values,
     CultureInfo culture)
 {
     var backingStore = new FormCollection(values);
     return new FormValueProvider(bindingSource, backingStore, culture);
 }
Example #8
0
        public async Task<IActionResult> Project(int? id, FormCollection form)
        {
            var project = await _db.Projects.SingleOrDefaultAsync(x => x.Id == id)
                          ?? _db.Projects.Add(new Project()).Entity;

            await TryUpdateModelAsync(project);
            await _db.SaveChangesAsync();

            return RedirectToAction("Index");
        }
        public ActionResult ReturnFileContent(FormCollection form)
        {
            var file = form.Files.GetFile("File");
            using (var reader = new StreamReader(file.OpenReadStream()))
            {
                var fileContent = reader.ReadToEnd();

                return Content(fileContent);
            }
        }
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage();

            if (request.RequestUri.AbsoluteUri.StartsWith("https://api.twitter.com/oauth/access_token"))
            {
                var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync()));
                if (formData["oauth_verifier"] == "valid_oauth_verifier")
                {
                    if (_requestTokenEndpointInvoked)
                    {
                        var response_Form_data = new List<KeyValuePair<string, string>>()
                            {
                                new KeyValuePair<string, string>("oauth_token", "valid_oauth_token"),
                                new KeyValuePair<string, string>("oauth_token_secret", "valid_oauth_token_secret"),
                                new KeyValuePair<string, string>("user_id", "valid_user_id"),
                                new KeyValuePair<string, string>("screen_name", "valid_screen_name"),
                            };

                        response.Content = new FormUrlEncodedContent(response_Form_data);
                    }
                    else
                    {
                        response.StatusCode = HttpStatusCode.InternalServerError;
                        response.Content = new StringContent("RequestTokenEndpoint is not invoked");
                    }
                    return response;
                }
                response.StatusCode = (HttpStatusCode)400;
                return response;
            }
            else if (request.RequestUri.AbsoluteUri.StartsWith("https://api.twitter.com/oauth/request_token"))
            {
                var response_Form_data = new List<KeyValuePair<string, string>>()
                {
                    new KeyValuePair<string, string>("oauth_callback_confirmed", "true"),
                    new KeyValuePair<string, string>("oauth_token", "valid_oauth_token"),
                    new KeyValuePair<string, string>("oauth_token_secret", "valid_oauth_token_secret")
                };

                _requestTokenEndpointInvoked = true;
                response.Content = new FormUrlEncodedContent(response_Form_data);
                return response;
            }

            throw new NotImplementedException(request.RequestUri.AbsoluteUri);
        }
        public async Task FormCollectionModelBinder_FormCollectionConcreteType_BindFails()
        {
            // Arrange
            var formCollection = new FormCollection(new Dictionary<string, StringValues>
            {
                { "field1", "value1" },
                { "field2", new string[] { "value2" } }
            });
            var httpContext = GetMockHttpContext(formCollection);
            var bindingContext = GetBindingContext(typeof(FormCollection), httpContext);
            var binder = new FormCollectionModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.Equal(ModelBindingResult.NoResult, result);
        }
        public async Task FormCollectionModelBinder_InvalidType_BindFails()
        {
            // Arrange
            var formCollection = new FormCollection(new Dictionary<string, string[]>
            {
                { "field1", new string[] { "value1" } },
                { "field2", new string[] { "value2" } }
            });
            var httpContext = GetMockHttpContext(formCollection);
            var bindingContext = GetBindingContext(typeof(string), httpContext);
            var binder = new FormCollectionModelBinder();

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.Null(result);
        }
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage();

            if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.5/oauth/access_token"))
            {
                var formData = new FormCollection(await FormReader.ReadFormAsync(await request.Content.ReadAsStreamAsync()));
                if (formData["grant_type"] == "authorization_code")
                {
                    if (formData["code"] == "ValidCode")
                    {
                        Helpers.ThrowIfConditionFailed(() => ((string)formData["redirect_uri"]).EndsWith("signin-facebook"), "Redirect URI is not ending with /signin-facebook");
                        Helpers.ThrowIfConditionFailed(() => formData["client_id"] == "[AppId]", "Invalid client Id received");
                        Helpers.ThrowIfConditionFailed(() => formData["client_secret"] == "[AppSecret]", "Invalid client secret received");
                        response.Content = new StringContent("{ \"access_token\": \"ValidAccessToken\", \"expires_in\": \"100\" }");
                        return response;
                    }
                    response.StatusCode = (HttpStatusCode)400;
                    return response;
                }
            }
            else if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.5/me"))
            {
                var queryParameters = new QueryCollection(QueryHelpers.ParseQuery(request.RequestUri.Query));
                Helpers.ThrowIfConditionFailed(() => queryParameters["appsecret_proof"].Count > 0, "appsecret_proof is empty");
                if (queryParameters["access_token"] == "ValidAccessToken")
                {
                    response.Content = new StringContent("{\"id\":\"Id\",\"name\":\"AspnetvnextTest AspnetvnextTest\",\"first_name\":\"AspnetvnextTest\",\"last_name\":\"AspnetvnextTest\",\"link\":\"https:\\/\\/www.facebook.com\\/myLink\",\"username\":\"AspnetvnextTest.AspnetvnextTest.7\",\"gender\":\"male\",\"email\":\"AspnetvnextTest\\u0040test.com\",\"timezone\":-7,\"locale\":\"en_US\",\"verified\":true,\"updated_time\":\"2013-08-06T20:38:48+0000\",\"CertValidatorInvoked\":\"ValidAccessToken\"}");
                }
                else
                {
                    response.Content = new StringContent("{\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190}}");
                }
                return response;
            }

            throw new NotImplementedException(request.RequestUri.AbsoluteUri);
        }
        private static void SetFormFileBodyContent(HttpRequest request, string content, string name)
        {
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, string[]>(), fileCollection);
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content));

            request.Form = formCollection;
            request.ContentType = "multipart/form-data";
            request.Headers["Content-Disposition"] = "form-data; name=" + name + "; filename=text.txt";

            fileCollection.Add(new FormFile(memoryStream, 0, memoryStream.Length)
            {
                Headers = request.Headers
            });
        }
Example #15
0
 public string Index(FormCollection fc, string searchString)
 {
     return "From [HttpPost]Index: filter on " + searchString;
 }
        private static void SetFormFileBodyContent(HttpRequest request, string content, string name)
        {
            const string fileName = "text.txt";
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, StringValues>(), fileCollection);
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content));

            request.Form = formCollection;
            request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq";
            request.Headers["Content-Disposition"] = $"form-data; name={name}; filename={fileName}";

            fileCollection.Add(new FormFile(memoryStream, 0, memoryStream.Length, name, fileName)
            {
                Headers = request.Headers
            });
        }
        private void UpdateRequest(HttpRequest request, string data, string name)
        {
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, string[]>(), fileCollection);

            request.Form = formCollection;
            request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq";

            if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(name))
            {
                // Leave the submission empty.
                return;
            }

            request.Headers["Content-Disposition"] = "form-data; name=" + name + "; filename=text.txt";

            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(data));
            fileCollection.Add(new FormFile(memoryStream, 0, data.Length)
            {
                Headers = request.Headers
            });
        }
        private async Task<IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken)
        {
            if (!HasFormContentType)
            {
                throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
            }

            cancellationToken.ThrowIfCancellationRequested();

            _request.EnableRewind();

            FormCollection formFields = null;
            FormFileCollection files = null;

            // Some of these code paths use StreamReader which does not support cancellation tokens.
            using (cancellationToken.Register((state) => ((HttpContext)state).Abort(), _request.HttpContext))
            {
                var contentType = ContentType;
                // Check the content-type
                if (HasApplicationFormContentType(contentType))
                {
                    var encoding = FilterEncoding(contentType.Encoding);
                    formFields = new FormCollection(await FormReader.ReadFormAsync(_request.Body, encoding, cancellationToken));
                }
                else if (HasMultipartFormContentType(contentType))
                {
                    var formAccumulator = new KeyValueAccumulator();

                    var boundary = GetBoundary(contentType);
                    var multipartReader = new MultipartReader(boundary, _request.Body);
                    var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    while (section != null)
                    {
                        ContentDispositionHeaderValue contentDisposition;
                        ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                        if (HasFileContentDisposition(contentDisposition))
                        {
                            // Find the end
                            await section.Body.DrainAsync(cancellationToken);

                            var name = HeaderUtilities.RemoveQuotes(contentDisposition.Name) ?? string.Empty;
                            var fileName = HeaderUtilities.RemoveQuotes(contentDisposition.FileName) ?? string.Empty;

                            var file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length, name, fileName)
                            {
                                Headers = new HeaderDictionary(section.Headers),
                            };
                            if (files == null)
                            {
                                files = new FormFileCollection();
                            }
                            files.Add(file);
                        }
                        else if (HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            MediaTypeHeaderValue mediaType;
                            MediaTypeHeaderValue.TryParse(section.ContentType, out mediaType);
                            var encoding = FilterEncoding(mediaType?.Encoding);
                            using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                            {
                                var value = await reader.ReadToEndAsync();
                                formAccumulator.Append(key, value);
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition);
                        }

                        section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    }

                    if (formAccumulator.HasValues)
                    {
                        formFields = new FormCollection(formAccumulator.GetResults(), files);
                    }
                }
            }

            // Rewind so later readers don't have to.
            _request.Body.Seek(0, SeekOrigin.Begin);

            if (formFields != null)
            {
                Form = formFields;
            }
            else if (files != null)
            {
                Form = new FormCollection(null, files);
            }
            else
            {
                Form = FormCollection.Empty;
            }

            return Form;
        }
        public async Task<IActionResult> ChangeEvent(FormCollection form)
        {
            bool oAllDay;
            Boolean.TryParse(form["original_allDay"], out oAllDay);
            string oName = form["original_title"];
            var oStart = DateTime.Parse(form["original_start"]);
            var oEnd = DateTime.Parse(form["original_end"]);

            bool allDay;
            Boolean.TryParse(form["allDay1"], out allDay);
            string name = form["Event Name"];
            var start = DateTime.Parse(form["StartDateTime"]);
            DateTime end;
            try
            {
                end = DateTime.Parse(form["EndDateTime"]);
            }
            catch (Exception)
            {

                end = start;
            }

            var user = await GetCurrentUserAsync();
            var events = _db.Events.Include(e => e.User)
                .Where(e => e.UserId.Equals(user.Id))
                .Where(e => e.StartTime.Equals(oStart) && e.EndTime.Equals(oEnd));

            foreach (var e in events)
            {
                e.AllDayEvent = allDay;
                e.NameOfEvent = name;
                e.StartTime = allDay ? start.Date : start;
                e.EndTime = allDay ? e.StartTime.AddDays(1) : end;
                _db.Events.Update(e);
                //return RedirectToAction("Index");
            }

            await _db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        public async Task CollectionModelBinder_UsesCustomIndexes()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor()
            {
                Name = "parameter",
                ParameterType = typeof(Person4)
            };

            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                var formCollection = new FormCollection(new Dictionary<string, string[]>()
                {
                    { "Addresses.index", new [] { "Key1", "Key2" } },
                    { "Addresses[Key1].Street", new [] { "Street1" } },
                    { "Addresses[Key2].Street", new [] { "Street2" } },
                });

                request.Form = formCollection;
                request.ContentType = "application/x-www-form-urlencoded";
            });

            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert
            Assert.NotNull(modelBindingResult);
            Assert.True(modelBindingResult.IsModelSet);
            Assert.IsType<Person4>(modelBindingResult.Model);

            Assert.Equal(2, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
            var entry = Assert.Single(modelState, kvp => kvp.Key == "Addresses[Key1].Street").Value;
            Assert.Equal("Street1", entry.Value.AttemptedValue);
            Assert.Equal("Street1", entry.Value.RawValue);

            entry = Assert.Single(modelState, kvp => kvp.Key == "Addresses[Key2].Street").Value;
            Assert.Equal("Street2", entry.Value.AttemptedValue);
            Assert.Equal("Street2", entry.Value.RawValue);
        }
        public async Task CollectionModelBinder_UsesCustomIndexes_AddsErrorsWithCorrectKeys()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor()
            {
                Name = "parameter",
                ParameterType = typeof(Person5)
            };

            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                var formCollection = new FormCollection(new Dictionary<string, string[]>()
                {
                    { "Addresses.index", new [] { "Key1" } },
                    { "Addresses[Key1].Street", new [] { "Street1" } },
                });

                request.Form = formCollection;
                request.ContentType = "application/x-www-form-urlencoded";
            });

            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert
            Assert.NotNull(modelBindingResult);
            Assert.True(modelBindingResult.IsModelSet);
            Assert.IsType<Person5>(modelBindingResult.Model);

            Assert.Equal(1, modelState.Count);
            Assert.Equal(1, modelState.ErrorCount);
            Assert.False(modelState.IsValid);

            var entry = Assert.Single(modelState, kvp => kvp.Key == "Addresses[Key1].Street").Value;
            var error = Assert.Single(entry.Errors);
            Assert.Equal("The field Street must be a string with a maximum length of 3.", error.ErrorMessage);
        }
 public IActionResult TrackProject(FormCollection form)
 {
     string emailAddress = Request.Form["email"];
     ViewData["emailAddress"] = Request.Form["email"];
     ViewData["projectCount"] = _context.Projects.ToList().Where(x => x.UserEmail == emailAddress).Count();
     return View();
 }
        private void UpdateRequest(HttpRequest request, string data, string name)
        {
            var fileCollection = new FormFileCollection();
            var formCollection = new FormCollection(new Dictionary<string, StringValues>(), fileCollection);
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(data));

            request.Form = formCollection;
            request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq";
            request.Headers["Content-Disposition"] = "form-data; name=" + name + "; filename=text.txt";
            fileCollection.Add(new FormFile(memoryStream, 0, data.Length)
            {
                Headers = request.Headers
            });
        }