简体   繁体   English

在.NET 4.5.1中发布到ASP.NET WebApi 2

[英]POST to ASP.NET WebApi 2 in .NET 4.5.1

How can I POST a complex type to a Web Api 2 controller action, from a C# client? 如何从C#客户端将复杂类型发布到Web Api 2控制器操作中? I see a lot of information about it but for older versions of the framework. 我看到了很多有关该框架的信息,但有关旧版本的框架。 What's the correct way to do it in .NET 4.5.1? 在.NET 4.5.1中执行此操作的正确方法是什么?

At the moment I have: 目前,我有:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:60892/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    //client.PostAsJsonAsync() doesn't seem to exist or I am missing something
    //client.PostAsync() can't find a way to post a complex type    

    if (response.IsSuccessStatusCode)
    {

    }
}

You will find the PostAsJsonAsync extension method in the Micorosft ASP.NET Web API 2.1 Client NuGet package . 您可以在Micorosft ASP.NET Web API 2.1客户端NuGet包中找到PostAsJsonAsync扩展方法。

Nevertheless, if you set the HttpContent appropriately the PostAsync method should work. 但是,如果适当地设置HttpContent,PostAsync方法应该起作用。 An example can be found in this discussion . 可以在此讨论中找到一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM