使用 WebClient 调用具有复杂对象参数的 WebApi

Calling WebApi with complex object parameter using WebClient

我需要使用 WebClient 调用 WebApi,其中必须将对象作为参数传递。我的 WebApi 方法类似于以下代码:

示例 URI:localhost:8080/Api/DocRepoApi/PostDoc

[HttpPost]
public string PostDoc (DocRepoViewModel docRepo)
{
  return string.enpty;
}

然后 DocRepoViewModel 是:

public class DocRepoViewModel
{
    public string Roles { get; set; }
    public string CategoryName { get; set; }
    public List<AttachmentViewModel> AttachmentInfo { get; set; }
}

AttachmentViewModel 是:

public class AttachmentViewModel
{
    public string AttachmentName { get; set; }

    public byte[] AttachmentBytes { get; set; }

    public string AttachmentType { get; set; }
}

新我需要从我的 MVC 控制器调用 PostDoc 方法(不是 javascript ajax)。我如何传递这个特定的参数,我可以进行调用并在我的 WebApi 方法中获取所有数据。我们可以通过 WebClient 完成吗?或者有更好的方法。请帮忙。

您可以使用 PostAsJsonAsync 方法如下:

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("localhost:8080/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP POST
        var docViewModel = new DocRepoViewModel() { CategoryName = "Foo", Roles= "role1,role2" };
        var attachmentInfo = new List<AttachmentViewModel>() { AttachmentName = "Bar", AttachmentType = "Baz", AttachmentBytes = File.ReadAllBytes("c:\test.txt" };
        docViewModel.AttachmentInfo = attachmentInfo;
        response = await client.PostAsJsonAsync("DocRepoApi/PostDoc", docViewModel);
        if (response.IsSuccessStatusCode)
        {
          // do stuff
        }
    }
}

Asp .net reference

查看以下代码。

    string url = "Your Url";

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.KeepAlive = false;
    request.ContentType = "application/json";
    request.Method = "POST";

    var entity = new Entity(); //your custom object.
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(entity));
    request.ContentLength = bytes.Length;

    Stream data = request.GetRequestStream();
    data.Write(bytes, 0, bytes.Length);
    data.Close();

    using (WebResponse response = request.GetResponse())
    {
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string message = reader.ReadToEnd();

            var responseReuslt = JsonConvert.Deserialize<YourDataContract>(message);
        }
    }