简体   繁体   中英

Calling WebApi with complex object parameter using WebClient

I need to call a WebApi using WebClient where have to pass an object as parameter. I have my WebApi method as similar to bellow code:

example URI: localhost:8080/Api/DocRepoApi/PostDoc

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

and then DocRepoViewModel is:

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

AttachmentViewModel is:

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

    public byte[] AttachmentBytes { get; set; }

    public string AttachmentType { get; set; }
}

New I need to call PostDoc method from my MVC controller (not javascript ajax). How can I pass this specific parameter that I can make the call and get all data in my WebApi method. Can we do it by WebClient ? Or there are better way. Please help.

You could use the PostAsJsonAsync method as follows:

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

Check out following code.

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

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