gpt4 book ai didi

asp.net-web-api - 如何让 ASP.Net Web API 和 OData 将字符串值绑定(bind)为键?

转载 作者:行者123 更新时间:2023-12-03 01:07:01 25 4
gpt4 key购买 nike

我正在学习来自 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; }
}

修改后的 Controller :

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”未绑定(bind)到 GetEntityByKey(string key) 中的 key 参数> 行动。但是,当我浏览到 odata/Products(1) 时,“1”确实会绑定(bind)到 key 参数。

如何获取包含文本值的字符串以正确绑定(bind),而不是仅将字符串与数值绑定(bind)?

更新

我忘记包含 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);
}
}

最佳答案

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

经过一番尝试后,我发现以下路径如我所愿:

/odata/Products('one')

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

关于asp.net-web-api - 如何让 ASP.Net Web API 和 OData 将字符串值绑定(bind)为键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com