如何正确使用HttpClient PostAsync参数?

时间:2017-12-22 16:13:31

标签: c# .net httpwebrequest httpclient httpwebresponse

所以我正在使用HttpClient为我的项目编写扩展类,因为我正在从HttpWebRequest转移。

在执行POST请求时,如何将普通字符串作为参数发送?没有json或任何东西只是一个简单的字符串。

到目前为止这就是它的样子。

static class HttpClientExtension
    {
        static HttpClient client = new HttpClient();
        public static string GetHttpResponse(string URL)
        {
            string fail = "Fail";
            client.BaseAddress = new Uri(URL);
            HttpResponseMessage Response = client.GetAsync(URL).GetAwaiter().GetResult();
            if (Response.IsSuccessStatusCode)
                return Response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            else
                return fail;
        }

        public static string PostRequest(string URI, string PostParams)
        {
            client.PostAsync(URI, new StringContent(PostParams));
            HttpResponseMessage response = client.GetAsync(URI).GetAwaiter().GetResult();
            string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            return content;
        }
    }

如果你看这个像

client.PostAsync(URI, new StringContent(PostParams));

你可以看到我只是尝试创建新的StringContent并将一个字符串传递给它,并且返回的404页面没有找到。 我如何正确使用Post.Async();发送字符串或字节数组?因为使用HttpWebRequest,你会这样做

public static void SetPost(this HttpWebRequest request, string postdata)
        {
            request.Method = "POST";
            byte[] bytes = Encoding.UTF8.GetBytes(postdata);

            using (Stream requestStream = request.GetRequestStream())
                requestStream.Write(bytes, 0, bytes.Length);
        }

2 个答案:

答案 0 :(得分:3)

PostRequest中完成以下操作..

client.PostAsync(URI, new StringContent(PostParams));
HttpResponseMessage response = client.GetAsync(URI).GetAwaiter().GetResult();

哪个不捕获POST的响应。

重构为

public static string PostRequest(string URI, string PostParams) {            
    var response = client.PostAsync(URI, new StringContent(PostParams)).GetAwaiter().GetResult();
    var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    return content;
}

HttpClient主要用于异步,因此请考虑重构

public static async Task<string> PostRequestAsync(string URI, string PostParams) {            
    var response = await client.PostAsync(URI, new StringContent(PostParams));
    var content = await response.Content.ReadAsStringAsync();
    return content;
}

答案 1 :(得分:1)

我已经完成了以下工作(使用Ngonzalez.ImageProcessorCore包)。

查询(ASP.NET Core 2 Controller):

async Task<byte[]> CreateImage(IFormFile file)
{
  using (var memoryStream = new MemoryStream())
  {
    await file.CopyToAsync(memoryStream);
    var image = new Image(memoryStream);
    var height = image.Height < 150 ? image.Height : 150;
    image.Resize((int)(image.Width * height / image.Height), height).Save(memoryStream);
    return memoryStream.ToArray();
  }
}

[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> ImageAdd(ImageAddVm vm)
{
  byte[] image = null;
  if (vm.File != null && vm.File.Length > 0)
     image = await CreateImage(vm.File);
  if (image != null)
  {
    var json = JsonConvert.SerializeObject(new { vm.ObjectId, image });
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    var client= new HttpClient();
    await client.PostAsync($"{ApiUrl}/SaveImage", content);
  }
  return RedirectToAction("ReturnAction");
}

Api(ASP.NET Core 2 Controller):

public class ObjectImage
{
  public int ObjectId { get; set; }
  public byte[] Image { get; set; }
}

[HttpPost("SaveImage")]
public void SaveImage([FromBody]object content)
{
  var obj = JsonConvert.DeserializeObject<ObjectImage>(content.ToString());
  _db.Images.Find(obj.ObjectId).Image = obj.Image;
  _db.SaveChanges();
}