【问题标题】:Calling WebApi with complex object parameter using WebClient使用 WebClient 调用具有复杂对象参数的 WebApi
【发布时间】:2015-02-03 15:18:35
【问题描述】:

我需要使用 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 控制器(不是 javascript ajax)调用 PostDoc 方法。我如何传递这个特定的参数,我可以在我的 WebApi 方法中进行调用并获取所有数据。我们可以通过WebClient 来做吗?或者有更好的方法。请帮忙。

【问题讨论】:

    标签: c# asp.net webclient asp.net-web-api


    【解决方案1】:

    你可以使用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

    【讨论】:

    • PostAsJsonAsync 不适用于所有库。例如,我在 HttpClient 中看不到此方法。也许现在已经过时了?
    • @alvinfromdiaspar 这不是过时的,请参阅此处以替代 v4.0 stackoverflow.com/questions/21266807/…
    【解决方案2】:

    查看以下代码。

        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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-03-15
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2020-10-03
      • 1970-01-01
      • 2016-07-21
      • 2012-07-14
      • 2017-05-13
      相关资源
      最近更新 更多