如何实现在向Rest API发出get请求时指定接收哪些参数的功能?

时间:2016-06-05 22:02:53

标签: c# sql rest asp.net-web-api

因为我需要减少API的负担,所以我考虑实现一种可能性来指定您希望根据请求接收哪些属性。

现在用户向api请求获取产品

/api/products/{id}

他们获取整个产品信息(id,name,Created Date,updatedDate,deleted,active等),因此我需要从数据库中提取所有这些属性。

我想要实现的是,api用户可以只选择他们想要接收的属性,而不是返回产品从服务器获得的所有属性。网址可能如下所示:

/products/{id}/props={id,name,LastUpdated}

所以我只需要从DB中选择id,name和LastUpdated以返回给API用户。

如何以最聪明的方式实际实现这样的功能?

4 个答案:

答案 0 :(得分:2)

编辑:现在问题已得到很好的描述。

我明白了。只有没有模型才能实现。 (我认为)

我认为JObject是一个好的开始,它可能是最受测试的库。

或多或少应该是这样的:

  1. 解析查询字符串

  2. 获取这些字段并从数据库中进行选择。 (如果使用sql server,你可以在里面有一个带有动态查询的存储过程。

  3. 获取结果并将其解析为json这里是newtonsoft的便利之处。

  4. 返回Json。

答案 1 :(得分:0)

OData就是您所需要的。它允许您指定需要在URL中进行检索的属性,然后生成只返回这些特定属性的数据库查询。

基础教程(来自官方网站):http://www.odata.org/getting-started/basic-tutorial/

答案 2 :(得分:0)

例如,您可以执行此类操作,但可以根据您的API需求进行编辑

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using System.Linq;

public class Program
{

    public class Man
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
    }

    public static void Main()
    {
        var man = new Man
        {
            Id = 2,
            Name = "A Name",
            Phone = "123456789"
        };

        var props = "id,name";

        var customPropsArray = props.Split(',');

        Type t = man.GetType();
        PropertyInfo[] properties = t.GetProperties(
            BindingFlags.NonPublic | // Include protected and private properties
            BindingFlags.Public | // Also include public properties
            BindingFlags.Instance // Specify to retrieve non static properties
            );

        var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;

        foreach (var p in properties.Where(x => customPropsArray.Contains(x.Name.ToLower())))
        {           
            dynamicObject.Add(p.Name, p.GetValue(man));
        }
    }
}

答案 3 :(得分:0)

OData是一个好主意,但是如果由于某种原因你不能使用它,你可以使用enum来指定你想要的属性,然后通过Dictionary将它们在你的API中序列化为Json 。像这样:

[Flags]
public enum Props
{
    FirstName = 1,
    Surname = 2,
    Address = 4,
    Occupation = 8
}

public string GetValues(int id, Props props)
{
    var items = new Dictionary<string, string>();

    if (props == 0 || props.HasFlag(Props.FirstName))
        items.Add("FirstName", "Bob");

    if (props == 0 || props.HasFlag(Props.Surname))
        items.Add("Surname", "Smith");

    if (props == 0 || props.HasFlag(Props.Address))
        items.Add("Address", "London");

    if (props == 0 || props.HasFlag(Props.Occupation))
        items.Add("Occupation ", "Professional Tea Drinker");

    //Using Newtonsoft Json:
    return JsonConvert.SerializeObject(items);
}

你这样称呼它:

GetValues(1, (Props)0)
GetValues(1, (Props)1)
GetValues(1, (Props)3)

返回:

  

{“FirstName”:“Bob”,“Surname”:“Smith”,“Address”:“London”,“Occupation”:“Professional Tea Drinker”}

     

{ “姓”: “鲍勃”}

     

{ “姓”: “鲍勃”, “姓”: “史密斯”}