我如何消耗asp.net MVC 3非WCF休息服务? [英] How do I consume a non-wcf rest service in asp.net mvc 3?
问题描述
我有我写使用WebMatrix中,在返回的JSON数据的简单Web服务。我喜欢消耗使用ASP.NET MVC 3.服务,我知道如何与WCF做到这一点,但我们不打算使用WCF在这个项目上。是否有一个类似于jQuery的的getJSON()在ASP.NET MVC方法,我只是通过在宁静的URL并返回数据,我处理它在回调?感谢您的帮助: - )
下面是我的服务:
网址:
/服务/ GetAllItemsService
code:
@ {
变种项= ItemsService.GetAllItems(); Json.Write(物品,Response.Output);
}
您可以使用的 WebClient的从远程资源获取JSON数据。例如:
使用(VAR的客户=新的WebClient())
{
JSON字符串= client.DownloadString(http://example.com/services/GetAllItemsService); // TODO:做一些与此JSON数据,例如像反序列化到模型
VAR串行=新的JavaScriptSerializer();
VAR模型= serializer.Deserialize< SomeModel>(JSON);
}
或者,如果你想直接写JSON的输出:
使用(VAR的客户=新的WebClient())
{
JSON字符串= client.DownloadString(http://example.com/services/GetAllItemsService);
Response.Output.Write(JSON);
}
I have a simple web service I wrote using Webmatrix that returns data in json. I liked to consume that service using ASP.NET MVC 3. I know how to do this with WCF but we are not going to use WCF on this project. Is there something akin to jquery's getJson() method in ASP.NET MVC where I just pass in the restful url and it returns the data and I handle it in a callback? Thanks for any help :-)
Here's my service:
URL:
/services/GetAllItemsService
Code:
@{
var items = ItemsService.GetAllItems();
Json.Write(items, Response.Output);
}
You could use a WebClient to fetch the JSON data from a remote resource. For example:
using (var client = new WebClient())
{
string json = client.DownloadString("http://example.com/services/GetAllItemsService");
// TODO: do something with this JSON data, like for example deserialize into a model
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize<SomeModel>(json);
}
Or if you wanted to write the JSON directly to the output:
using (var client = new WebClient())
{
string json = client.DownloadString("http://example.com/services/GetAllItemsService");
Response.Output.Write(json);
}
这篇关于我如何消耗asp.net MVC 3非WCF休息服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!