在 Asp.Net MVC 2 和 Asp.Net 服务器端 C# 代码之间共享 Json 数据?
我创建并喜欢我的 Asp.Net MVC2 应用程序。这是一个非常好的 DDD 应用程序,具有域模型类、视图模型类、存储库和用于公开数据的 Json 操作方法。
我的同事想要与他基于 Asp.Net Forms 的 C# 代码共享我的数据。他想通过互联网获取一个类定义(如数据契约),然后用我的 Json 结果填充它,有效地使用远程存储库之类的东西。
有关如何向他提供数据合约和数据的任何链接或想法吗?
Darin Dimitrov 此处有一个使用数据合约使用 JSON 数据的好主意。只是想知道是否可以使用 MVC 作为这些项目的源,然后让他在他这边创建对象,并填充我这边的数据。
这个问题的关键是如何将我的数据类发送给他,然后将我的数据发送给他。
class Program
{
[DataContract]
class Person
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "surname")]
public string Surname { get; set; }
[DataMember(Name="age")]
public int Age { get; set; }
}
static void Main(string[] args)
{
var json = @"{""name"" : ""michael"", ""surname"" : ""brown"", ""age"" : ""35""}";
var serializer = new DataContractJsonSerializer(typeof(Person));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var person = (Person)serializer.ReadObject(stream);
Console.WriteLine("Name : {0}, Surname : {1}, Age : {2}",
person.Name, person.Surname, person.Age);
}
}
}
I created and love my Asp.Net MVC2 application. It's a very nice DDD app with Domain Model classes, View Model classes, a repository, and Json action methods to expose data.
My coworker wants to share my data with his Asp.Net Forms based C# code. He wants to pull through the Internet a class definition (like a Data Contract), then fill it with my Json results, effectively using something like a remote repository.
Any links or ideas on how to provide him with data contracts and data?
Darin Dimitrov had an excellent idea of consuming JSON data using data contracts here. Just wondering if it's possible to use MVC as the source for these items, then let him create the objects on his side, filled with data from my side.
The key to this question is how to send him my data classes, then send him my data.
class Program
{
[DataContract]
class Person
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "surname")]
public string Surname { get; set; }
[DataMember(Name="age")]
public int Age { get; set; }
}
static void Main(string[] args)
{
var json = @"{""name"" : ""michael"", ""surname"" : ""brown"", ""age"" : ""35""}";
var serializer = new DataContractJsonSerializer(typeof(Person));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var person = (Person)serializer.ReadObject(stream);
Console.WriteLine("Name : {0}, Surname : {1}, Age : {2}",
person.Name, person.Surname, person.Age);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编写 OData 服务。格式是 JSON,但可以轻松使用它的工具 - 来自许多语言 - 已经为您编写了。
这样做的好处是,您的数据现在不仅可以由您的 JS 和您朋友的 ASP.NET 应用程序使用,还可以由 Excel、PHP 等使用。
Write an OData service. The format is JSON, but the tools to consume it easily -- from many languages -- are already written for you.
The nice thing about this is that your data is now not only consumable by your JS and your friend's ASP.NET app, it's consumable by Excel, PHP, etc.