简体   繁体   中英

c# redirect post request

Trying to make a post request from one application to another using the same Form Data parameters that the first one received. both application controller currently have same method:

public async Task<ActionResult> TestSet()
    {
        var inputString = Request.Form["inputString"];
        var inputFile = Request.Files[0];
        var resultString = await _service.Set(inputString, inputFile.FileName, inputFile.ContentType, inputFile.InputStream);
        return new MyJsonResult(new
        {
            fileName = resultString
        });
    }

which return json string:

{"fileName": "someFileName.png"}

Trying to make the first method to be something like this

public async Task<ActionResult> TestSet()
    {
        var inputString = Request.Form["inputString"];
        var inputFile = Request.Files[0];
        if (!string.IsNullOrEmpty(_redirectUrl))
        {
            using (var client = new HttpClient())
            {
                HttpContent content = GetContentSomehow(this.Request); // this i have an issue with
                var response = await client.PostAsync(_redirectUrl, content);
                var responseString = await response.Content.ReadAsStringAsync();
                return new MyJsonResult(responseString);
            }
        }
        var resultString = await _service.Set(inputString, inputFile.FileName, inputFile.ContentType, inputFile.InputStream);
        return new MyJsonResult(new
        {
            fileName = resultString
        });
    }

This could help to get ByteArrayContent for File only.

And this would probably work to get the non-file parameters into StringContent, but how to get both of them into single Content?

var jsonString = JsonConvert.SerializeObject(Request.Form.ToDictionary());
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");

Solved this issue by cominig StringContent and StreamContent into MultipartFormDataContent

public static MultipartFormDataContent GetMultipartFormData(HttpRequestBase req)
    {
        var formData = new MultipartFormDataContent();
        //formData.Headers.ContentType.MediaType = "multipart/form-data";
        foreach (var row in req.Form.ToDictionary())
        {
            formData.Add(new StringContent(row.Value), row.Key);
        }

        var file = req.Files[0];
        StreamContent fileStreamContent = new StreamContent(file.InputStream);
        fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
        formData.Add(fileStreamContent, file.FileName, file.FileName);

        return formData;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM