简体   繁体   中英

Making an async HttpClient post request with data from FormCollection

I am doing an Asp.Net MVC 4 project and am looking to an internal request (like a proxy) to our api service.

This is what the index method looks like in my controller. I'm stuck at the PostAsync part.

[HttpPost]
public async Task<ActionResult> Index(FormCollection body){

   HttpClient httpClient  = new HttpClient();
   httpClient.BaseAddress = new Uri("http://myapi.com");

   // posts to http://myapi.com/users
   var response = await httpClient.PostAsync("users", body);

   if(response.isSuccessStatusCode) return Json(new {
        status = true,
        url    = response.Content.Url
   });
}

I want to pass my "application/x-form-urlencoded" "body" content to the PostAsync POST method. However, I get an error reading "body is not of type HttpContent".

I can't cast or convert. What now?

Let me know what I'm doing incorrectly here.

Erik

I'm not entirely sure what you're trying to do, but possibly converting the FormCollection to a dictionary and using the FormUrlEncodedContent class is what you're looking for.

eg:

var response = await httpClient.PostAsync("users",
                                          new FormUrlEncodedContent(
                                              body.
                                                  AllKeys.ToDictionary(
                                                      k => k, v => body[v])));

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