本文介绍了我如何将数据传递到ASP.NET的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力通过在asp.net网站上的新的WebAPI过来。我用简单的字符串,我可以创造几样。我想看看,如果我现在可以POST并投入服务。

I have been working through the new WebAPI over on the asp.net site. 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或从.NET 3.5的控制台应用程序把请求。我想送的对象只是一个简单的用户类名字,姓氏和用户名。

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. The object I am trying to send is just a simple User class with Name, Surname, and UserID.

从我的测试看来,我可以序列化这一点,并通过URI发送但这似乎不是正确的。我注意到,这些要求都头,我可以把数据在那里?

From my testing it seems that I can serialize this and send it via the URI but that hardly seems correct. I notice that these requests have headers, can I put the data in there?

推荐答案

使用.NET 3.5,不会有太多的选择高雅,我认为,但使用这种code Web客户端作品(你需要添加引用System.Web.Extensions程序):

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):

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"

这是控制器动作:

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

这篇关于我如何将数据传递到ASP.NET的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:41
查看更多