我需要使用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
来做吗?或者有更好的方法。请帮忙。
答案 0 :(得分: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
}
}
}
答案 1 :(得分:0)
查看以下代码。
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);
}
}