Search code examples
.net-coreasp.net-core-webapidotnet-httpclient

HttpClient copy data from Request.Form .NET Core


I have POST query with Form data with files and I need to send the same data to another POST request. I'm going to use for this HttpClient class.

Is there a way to copy all Request.Form data and insert them to new request? Or I need to add every param?

I mean something like this:

var httpClient = new HttpClient();
var httpResponseMessage = await httpClient.PostAsync("some_url", Request.Form);

Solution

  • Is there a way to copy all Request.Form data and insert them to new request? Or I need to add every param?

    You need to add every param like below:

    Model in ProjectA:

    public class FormData
    {
        public int Id { get; set; }
        public IFormFile File { get; set; }
        public string Name { get; set; }
    }
    

    View in ProjectA:

    @model FormData
    <form asp-action="Post" enctype="multipart/form-data">
        <div>
            Id:<input asp-for="Id"/>
        </div>
        <div>
            Name:<input asp-for="Name"/>
        </div>
        <div>
            FIle:<input asp-for="File" />
        </div>
        <div>
            <input type="submit" value="create" />
        </div>
    </form>
    

    Controller in ProjectA:

    [HttpPost]
    public async Task<IActionResult> Post(FormData formData)
    {
        HttpClient client = new HttpClient();
        // var formData = HttpContext.Request.Form;
        client.BaseAddress = new Uri("http://localhost:63331");//your applicationUrl
        client.DefaultRequestHeaders.Accept.Clear();
    
        var multiContent = new MultipartFormDataContent();
    
        var file = formData.File;
        if (file != null)
        {
            var fileStreamContent = new StreamContent(file.OpenReadStream());
            multiContent.Add(fileStreamContent, "File", file.FileName);
        }
    
        multiContent.Add(new StringContent(formData.Id.ToString()), "id");
        multiContent.Add(new StringContent(formData.Name.ToString()), "name");
    
    
        var response = await client.PostAsync("/api/values", multiContent);
        //do your stuff...
        return Ok();
    }
    

    Model in ProjectB:

    public class FormDataModel
    {
        public int Id { get; set; }
        public IFormFile File { get; set; }
        public string Name { get; set; }
    }
    

    Controller in ProjectB:

    [HttpPost]
    public void Post([FromForm]FormDataModel model)
    {
          //...
    }
    

    Result: enter image description here