【问题标题】:How I can use OData services with MVC4?如何在 MVC4 中使用 OData 服务?
【发布时间】:2013-07-14 04:44:58
【问题描述】:

在我的项目 CloudMiddleware 中,有用于与 PayPal、Twilio 等 API 集成的服务。我有 SOAP、REST 和 AJAX 请求的端点,我还想使用 ODATA 灵活性,因为请求是通过 HTTP 使用 url 本身.这可能吗?

【问题讨论】:

    标签: asp.net asp.net-mvc-4 asp.net-web-api odata


    【解决方案1】:

    假设您有一个服务控制器。每个服务都是具有 Id 和 Description 的类的实例。服务类具有 Id 和 Description 属性。

    public class ServiceController : ApiController
    {
        // GET api/service
        public IEnumerable<Service> Get()
        {
            return new Service[]
                        {
                            new Service { Id = 1, Description = "This is my service 1." },
                            new Service {Id = 2, Description = "This is my service 2."},
                            new Service {Id = 3, Description = "This is my service 3."}
                        };
        }
    
        // GET api/service/5
        public Service Get(int id)
        {
            return null;
        }
    
        // POST api/service
        public void Post([FromBody]string value)
        {
        }
    }
    
    public class  Service 
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }
    

    为了通过OData使用控制器的服务,你必须在“Get”方法中使用属性[Queryable]并将返回类型更改为IQueryable,一切准备就绪!!!!!!,如下:

    public class ServiceController : ApiController
    {
        // GET api/service
        [Queryable(ResultLimit = 10)]
        public IQueryable<Service> Get()
        {
            return new Service[]
                        {
                            new Service { Id = 1, Description = "This is my service 1." },
                            new Service {Id = 2, Description = "This is my service 2."},
                            new Service {Id = 3, Description = "This is my service 3."}
                        }.AsQueryable();
        }
    
        // GET api/service/5
        public Service Get(int id)
        {
            return null;
        }
    
        // POST api/service
        public void Post([FromBody]string value)
        {
        }
    }
    

    属性Queryable有属性ResultLimit,用来表示能容纳结果的服务实例的最大数量。它还具有 LambdaNestingLimitHandleNullPropagationEnsureStableOrdering 属性。

    对 /api/service?$top=2 的请求返回 Json 响应:

    { { "Id": "1", "Description": "这是我的服务 1."}, { "Id": "2", "Description": "这是我的服务 2."}}

    【讨论】:

      【解决方案2】:

      是的,您可以使用 ASP.NET Web API 或 WCF 数据服务在 ASP.NET MVC 项目中创建 OData 端点。前者为您在端点的实现中提供了更多的控制和灵活性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-03
        • 2016-03-03
        • 1970-01-01
        • 1970-01-01
        • 2012-07-28
        • 1970-01-01
        • 1970-01-01
        • 2018-09-23
        相关资源
        最近更新 更多