首页 后端开发 C#.Net教程 [转]Support Composite Key in ASP.NET Web API OData

[转]Support Composite Key in ASP.NET Web API OData

Jun 17, 2017 pm 04:33 PM
api asp.net web

本文转自:

he default EntitySetController doesn't support composite keys. So if you have composite key models, you need some additional work. Here is an example about how to do that.

The model is simple:

<code>public class Person
{
    [Key]
    public string FirstName { get; set; }
    [Key]
    public string LastName { get; set; }

    public int Age { get; set; }
}
</code>
登录后复制

The odata url for this model will look like:

<code>GET http://localhost:33051/People(FirstName='Kate',LastName='Jones') HTTP/1.1
</code>
登录后复制

And we want to have strong typed parameters in web api actions to this URL.

<code>    public Person Get([FromODataUri] string firstName, [FromODataUri] string lastName)
</code>
登录后复制

Note that the FromODataUri model binder attribute is used to parse from odata uri representation to clr type. In odata, string value is "'xxx'" and we want it to be "xxx".

In order to make the route to work, you can add a custom routing convention to parse the key path. Here is a sample implementation:

<code>public class CompositeKeyRoutingConvention : EntityRoutingConvention
{
    public override string SelectAction(System.Web.Http.OData.Routing.ODataPath odataPath, System.Web.Http.Controllers.HttpControllerContext controllerContext, ILookup<string, System.Web.Http.Controllers.HttpActionDescriptor> actionMap)
    {
        var action = base.SelectAction(odataPath, controllerContext, actionMap);
        if (action != null)
        {
            var routeValues = controllerContext.RouteData.Values;
            if (routeValues.ContainsKey(ODataRouteConstants.Key))
            {
                var keyRaw = routeValues[ODataRouteConstants.Key] as string;
                IEnumerable<string> compoundKeyPairs = keyRaw.Split(',');
                if (compoundKeyPairs == null || compoundKeyPairs.Count() == 0)
                {
                    return action;
                }

                foreach (var compoundKeyPair in compoundKeyPairs)
                {
                    string[] pair = compoundKeyPair.Split('=');
                    if (pair == null || pair.Length != 2)
                    {
                        continue;
                    }
                    var keyName = pair[0].Trim();
                    var keyValue = pair[1].Trim();

                    routeValues.Add(keyName, keyValue);
                }
            }
        }

        return action;
    }
}
</code>
登录后复制

The convention is inherited from EntityRoutingConvention, which is the default convetion to handle entity key. By calling base.SelectAction, it will add the full key path into routeValues. The new convention will check if it contains "," and seperate it into multiple keys and set each of them into routeValues. So when web api select actions, it will use those values to determine which action to choose. If there is no "," found, it behaves same as base convetion.

To register the convetion, you need to set it when mapping odata route:

<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableQuerySupport();

        var mb = new ODataConventionModelBuilder(config);
        mb.EntitySet<Person>("People");

        var conventions = ODataRoutingConventions.CreateDefault();
        conventions.Insert(0, new CompositeKeyRoutingConvention());

        config.Routes.MapODataRoute(
            routeName: "OData", 
            routePrefix: null, 
            model: mb.GetEdmModel(), 
            pathHandler: new DefaultODataPathHandler(), 
            routingConventions: conventions);
    }
}
</code>
登录后复制

Register the route at the postion 0 is to make it be executed before other default routing convetions. So the default EntityRoutingConvetion won't be executed before it. After that, you should be able to get routing work.

Then, how to build url for composite keys? 
You don't need to do that for odata links include edit link and self link when using ODataConventionModelBuilder. It will automatically identify composite keys and build the uri for you.

However, you need to build the link for location header. Here is a sample code from PeopleController.cs to handle post request:

<code>public HttpResponseMessage PostPerson(Person person)
{
    if (ModelState.IsValid)
    {
        _repo.UpdateOrAdd(person);

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, person);
        string key = string.Format(
            "{0}={1},{2}={3}",
            "FirstName", ODataUriUtils.ConvertToUriLiteral(person.FirstName, Microsoft.Data.OData.ODataVersion.V3),
            "LastName", ODataUriUtils.ConvertToUriLiteral(person.LastName, Microsoft.Data.OData.ODataVersion.V3));
        response.Headers.Location = new Uri(Url.ODataLink(
            new EntitySetPathSegment("People"),
            new KeyValuePathSegment(key)));
        return response;
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}
</code>
登录后复制

Hope it helps.

 

以上是[转]Support Composite Key in ASP.NET Web API OData的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1662
14
CakePHP 教程
1418
52
Laravel 教程
1311
25
PHP教程
1261
29
C# 教程
1234
24
Oracle API使用指南:探索数据接口技术 Oracle API使用指南:探索数据接口技术 Mar 07, 2024 am 11:12 AM

Oracle是一家全球知名的数据库管理系统提供商,其API(ApplicationProgrammingInterface,应用程序接口)是一种强大的工具,可帮助开发人员轻松地与Oracle数据库进行交互和集成。在本文中,我们将深入探讨OracleAPI的使用指南,向读者展示如何在开发过程中利用数据接口技术,同时提供具体的代码示例。1.Oracle

React API调用指南:如何与后端API进行交互和数据传输 React API调用指南:如何与后端API进行交互和数据传输 Sep 26, 2023 am 10:19 AM

ReactAPI调用指南:如何与后端API进行交互和数据传输概述:在现代的Web开发中,与后端API进行交互和数据传输是一个常见的需求。React作为一个流行的前端框架,提供了一些强大的工具和功能来简化这一过程。本文将介绍如何使用React来调用后端API,包括基本的GET和POST请求,并提供具体的代码示例。安装所需的依赖:首先,确保在项目中安装了Axi

如何处理Laravel API报错问题 如何处理Laravel API报错问题 Mar 06, 2024 pm 05:18 PM

标题:如何处理LaravelAPI报错问题,需要具体代码示例在进行Laravel开发时,经常会遇到API报错的情况。这些报错可能来自于程序代码逻辑错误、数据库查询问题或是外部API请求失败等多种原因。如何处理这些报错是一个关键的问题,本文将通过具体的代码示例来演示如何有效处理LaravelAPI报错问题。1.错误处理在Laravel

Oracle API集成策略解析:实现系统间无缝通信 Oracle API集成策略解析:实现系统间无缝通信 Mar 07, 2024 pm 10:09 PM

OracleAPI集成策略解析:实现系统间无缝通信,需要具体代码示例在当今数字化时代,企业内部系统之间需要相互通信和数据共享,而OracleAPI就是帮助实现系统间无缝通信的重要工具之一。本文将从OracleAPI的基本概念和原理入手,探讨API集成的策略,最终给出具体的代码示例帮助读者更好地理解和应用OracleAPI。一、OracleAPI基本

web标准是什么东西 web标准是什么东西 Oct 18, 2023 pm 05:24 PM

Web标准是一组由W3C和其他相关组织制定的规范和指南,它包括HTML、CSS、JavaScript、DOM、Web可访问性和性能优化等方面的标准化,通过遵循这些标准,可以提高页面的兼容性、可访问性、可维护性和性能。Web标准的目标是使Web内容能够在不同的平台、浏览器和设备上一致地展示和交互,提供更好的用户体验和开发效率。

开发建议:如何利用ThinkPHP框架进行API开发 开发建议:如何利用ThinkPHP框架进行API开发 Nov 22, 2023 pm 05:18 PM

开发建议:如何利用ThinkPHP框架进行API开发随着互联网的不断发展,API(ApplicationProgrammingInterface)的重要性也日益凸显。API是不同应用程序之间进行通信的桥梁,它可以实现数据共享、功能调用等操作,为开发者提供了相对简单和快速的开发方式。而ThinkPHP框架作为一款优秀的PHP开发框架,具有高效、可扩展和易用

如何从驾驶舱Web用户界面启用管理访问 如何从驾驶舱Web用户界面启用管理访问 Mar 20, 2024 pm 06:56 PM

Cockpit是一个面向Linux服务器的基于Web的图形界面。它主要是为了使新用户/专家用户更容易管理Linux服务器。在本文中,我们将讨论Cockpit访问模式以及如何从CockpitWebUI切换Cockpit的管理访问。内容主题:驾驶舱进入模式查找当前驾驶舱访问模式从CockpitWebUI启用Cockpit的管理访问从CockpitWebUI禁用Cockpit的管理访问结论驾驶舱进入模式驾驶舱有两种访问模式:受限访问:这是驾驶舱的默认访问模式。在这种访问模式下,您不能从驾驶舱Web用户

Insomnia教程:如何使用PHP API接口 Insomnia教程:如何使用PHP API接口 Jan 22, 2024 am 11:21 AM

PHPAPI接口:如何使用InsomniaInsomnia是一款功能强大的API测试和调试工具,它能够帮助开发者快速、方便地测试和验证API接口,支持多种编程语言和协议,其中包括PHP。本文将介绍如何使用Insomnia测试PHPAPI接口。第一步:安装InsomniaInsomnia是一款跨平台的应用程序,支持Windows、MacOS和Linux等

See all articles