加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 如何让ASP.Net Web API和OData将字符串值绑

发布时间:2020-12-16 07:17:33 所属栏目:asp.Net 来源:网络整理
导读:我将从asp.net: 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获得一个简短的Web Api OData教程. 我下载了示例项目,它的工作原理.但后来我开始使用他们
我将从asp.net: 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获得一个简短的Web Api OData教程.

我下载了示例项目,它的工作原理.但后来我开始使用他们在示例中使用的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,new Product() { stringKey = "three",ID = 3,Name = "Scarf",Price = 12,new Product() { stringKey = "four",ID = 4,Name = "Yo-yo",Price = 4.95M,Category = "Toys" },new Product() { stringKey = "five",ID = 5,Name = "Puzzle",Price = 8,};

    [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”没有绑定到GetEntityByKey(字符串键)操作中的key参数.但是,当我浏览odata / Products(1)时,“1”确实被绑定到关键参数.

如何才能获得具有正确绑定文本值的字符串,而不是仅使用数值绑定字符串?

更新

我忘了包含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”绑定为字符串键.

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

/odata/Products('one')

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读