如何让ASP.Net Web API和OData将字符串值绑定为键?

时间:2013-06-10 14:20:33

标签: asp.net-web-api odata

我正在浏览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);
    }
}

1 个答案:

答案 0 :(得分:8)

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

在玩了一些之后,我发现以下路径可以按照我的希望运行:

/odata/Products('one')

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