简体   繁体   English

如何将数据传递到ASP.NET WebAPI

[英]How do I pass data to an ASP.NET WebAPI

I have been working through the new WebAPI over on the asp.net site. 我一直在asp.net站点上浏览新的WebAPI。 I've created a few samples using simple strings that I can GET. 我使用可以获取的简单字符串创建了一些示例。 I am looking to see if I can now POST and PUT to the service. 我正在查看我现在是否可以对服务进行POST和PUT。

I am looking to see how I should add an object to the request that I can then POST or PUT from a .net 3.5 console application. 我正在寻找如何将对象添加到请求中,然后可以从.net 3.5控制台应用程序中进行POST或PUT操作。 The object I am trying to send is just a simple User class with Name, Surname, and UserID. 我尝试发送的对象只是一个简单的User类,具有Name,Surname和UserID。

From my testing it seems that I can serialize this and send it via the URI but that hardly seems correct. 从我的测试看来,我可以对其进行序列化并通过URI发送,但这似乎并不正确。 I notice that these requests have headers, can I put the data in there? 我注意到这些请求都有标头,我可以在其中放置数据吗?

Using .NET 3.5, there are not many elegant options I think but this code using WebClient works (you need adding reference to System.Web.Extensions): 使用.NET 3.5,我认为没有很多优雅的选择,但是使用WebClient这段代码有效(您需要添加对System.Web.Extensions的引用):

WebClient client = new WebClient();
JavaScriptSerializer serializer = new JavaScriptSerializer();
var data = serializer.Serialize(new {Name = "Ali", Title = "Ostad"});
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var downloadString = client.UploadString("http://localhost:59174/api/values", data); // value is "Ali"

And here is controller action: 这是控制器动作:

// POST /api/values
public string Post(JsonValue value)
{
    return value.AsDynamic().Name;
}

Check out the HttpClient on NuGet. 在NuGet上查看HttpClient This makes it easy to do most things over http. 这使通过http轻松执行大多数操作变得容易。

And here's an example of using it. 这是一个使用它的示例

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

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