5

我正在阅读来自 asp.net 的简短 Web Api + OData 教程:http ://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/getting-started-with -odata-in-web-api/create-a-read-only-odata-endpoint

我下载了示例项目,它可以工作。但后来我开始Product使用他们在示例中使用的模型。我添加了一个新属性来充当字符串类型的键而不是整数键。

新的 Product.cs:

public class Product
{
    public string stringKey { get; set; }
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

修改后的控制器:

public class ProductsController : EntitySetController<Product, string>
{
    static List<Product> products = new List<Product>()
    {
        new Product() { stringKey = "one", ID = 1, Name = "Hat", Price = 15, Category = "Apparel" },
        new Product() { stringKey = "two", ID = 2, Name = "Socks", Price = 5, Category = "Apparel" },
        new Product() { stringKey = "three", ID = 3, Name = "Scarf", Price = 12, Category = "Apparel" },
        new Product() { stringKey = "four", ID = 4, Name = "Yo-yo", Price = 4.95M, Category = "Toys" },
        new Product() { stringKey = "five", ID = 5, Name = "Puzzle", Price = 8, Category = "Toys" },
    };

    [Queryable]
    public override IQueryable<Product> Get()
    {
        return products.AsQueryable();
    }

    protected override Product GetEntityByKey(string key)
    {
        return products.FirstOrDefault(p => p.stringKey == key);
    }
}

麻烦的是,当我转到/odata/Products(one)字符串“one”时,它并没有绑定到GetEntityByKey(string key)动作中的关键参数。但是,当我浏览到odata/Products(1)“1”时确实会绑定到key参数。

如何正确绑定带有文本值的字符串,而不仅仅是绑定带有数值的字符串?

更新

我忘了包括 WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
        modelBuilder.EntitySet<Product>("Products");

        Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
        config.Routes.MapODataRoute("ODataRoute", "odata", model);
    }
}
4

1 回答 1

8

我注意到路径 /odata/Products(0011-1100) 只会将“0011”绑定为字符串键。

在玩了一些之后,我发现以下路径可以按我希望的那样工作:

/odata/Products('one')

似乎需要单引号来读取括号内的整个字符串。

于 2013-06-10T14:41:39.833 回答