创建模型和控制器
添加一个公共类Product。
namespace SelfHost
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
添加一个名为的公共类ProductsController。从System.Web.Http.ApiController派生此类。
namespace SelfHost
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public Product GetProductById(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
public IEnumerable<Product> GetProductsByCategory(string category)
{
return products.Where(p => string.Equals(p.Category, category,
StringComparison.OrdinalIgnoreCase));
}
}
}
只读属性:默认情况下,只读属性是序列化的
默认情况下,Json.NET保留时区。通过设置DateTimeZoneHandling属性覆盖它
var json=GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHanding=NewtonSoft.Json.DateTimeZoneHanding.Utc;
匿名和弱类型的对象
action方法可以返回匿名对象并将其序列华为JSON,如
public object Get(){
return new {
Name="",Age=23,Pets=new List<string>{ "Fido", "Polly", "Spot" }
}
}
XML序列化程序不支持匿名类型或JObject实例。如果将这些功能用于JSON数据,则应从管道中删除XML格式化程序,如本文后面所述。