简体   繁体   English

ASP.NET Web Api中可搜索GET端点的最佳实现

[英]Best implementation of a searchable GET endpoint in ASP.NET Web Api

I have a WebApi which exposes a Contact field in my database. 我有一个WebApi,它在数据库中公开了一个Contact字段。 Currently it has endpoints for Post (create), Put (edit), Get(return whole list), Get(int id) (return specific field). 当前,它具有Post(创建),Put(编辑),Get(返回整个列表),Get(整数id)(返回特定字段)的端点。

So the Get(int id) searches my DB for the contact with that id and returns it in JSON. 因此,Get(int id)在我的数据库中搜索具有该ID的联系人,并以JSON返回。 I would like to implement a method by which the user can submit conditions to my first Get function such as: 我想实现一种方法,用户可以通过该方法向我的第一个Get函数提交条件,例如:

GET  http://urlformyapi.com/api/apiContact/?querystring

Where the query string might be for example: 查询字符串可能是例如:

firstname=phil

And return all the Phil's. 并归还所有的Phil。

How is best to make this totally searchable for all of my data fields within contact? 如何最好地使其完全可搜索联系人中的所有数据字段?

    public int contactid { get; set; }

    [Required]
    public string firstname { get; set; }
    [Required]
    public string lastname { get; set; }
    [Required]
    public string email { get; set; }
    [Required]
    public string mobile { get; set; }

    public string company { get; set; }

    public string position { get; set;}

    public string notes { get; set; }

    public string image { get; set; }

I could do an initial get of the whole list and then go through each query parameter like: 我可以对整个列表进行初始获取,然后遍历每个查询参数,例如:

//where ContactList begins as the entire list of contacts.
if(notes != null){ ContactList = ContactList.Where(x => x.notes == notes).ToList(); }

Thus refining my list until returning it. 因此完善我的清单,直到返回为止。 But I wondered if there was an easier way which was more robust should my data model change/I want to make more fields searchable. 但是我想知道是否应该有一种更简便的方法,该方法更健壮,如果我的数据模型发生更改/我想使更多字段可搜索。

any thoughts? 有什么想法吗?

If you have a lot of similar API methods, you can take a look on OData . 如果您有很多类似的API方法,那么可以看看OData Another variant try to use for this purpose Dynamic Linq with custom filter formatting. 为此,另一种尝试使用Dynamic Linq和自定义过滤器格式的方法。 Otherwise my suggestion is create class which must contains query fields (search fields), for example: notes, ids, etc and then pass this object to API and filter your collections with those search fields and PredicateBuilder . 否则,我的建议是创建类,该类必须包含查询字段(搜索字段),例如:注释,ID等,然后将此对象传递给API并使用这些搜索字段和PredicateBuilder过滤您的集合。 Also good explanation how PredicateBuilder works. 也很好地解释了PredicateBuilder的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM