简体   繁体   English

Web API GET(全部),以及来自SQL Server的可选参数

[英]Web api GET (all) with optional parameters from SQL Server

I am creating a Web API GET (all) method with multiple optional parameters. 我正在创建具有多个可选参数的Web API GET(所有)方法。 I'm trying this with 1 parameter first but eventually I want 5 optional parameters. 我首先尝试使用1个参数,但最终我想要5个可选参数。 Starting with 1 parameter I have 2 situations: parameter is filled in and parameter is not filled in. 从1个参数开始,我有2种情况:参数已填写而参数未填写。

Parameter is filled in 参数填写

from r in db.requests
where r.status == status
select new Models.Request

Parameter is not filled in 参数未填写

from r in db.requests
select new Models.Request

I can not get both situations to work together so my question is: How can I combine these 2 situations? 我无法使两种情况都可以一起工作,所以我的问题是:如何结合这两种情况?

Controller 控制者

public IEnumerable<Request> Get(string status = "")
    {
        var requests = from r in db.requests
                       //where r.status == status
                       select new Models.Request
                       {
                           ID = r.ID,
                           ...more properties
                           };
            return (IEnumerable<Request>)requests;
    }

Route 路线

protected void Application_Start()
    {
        RouteTable.Routes.MapHttpRoute(
        name: "API Default",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });
    }

Try the following code: 尝试以下代码:

from r in db.requests
where r.status == status || status == ""
select new Models.Request

If status is empty string second part of the expression is true and all items will be returned no matter the value of the first part. 如果status为空字符串,则表达式的第二部分为true,无论第一部分的值如何,所有项都会返回。 Otherwise the first part of the expression filters the result set. 否则,表达式的第一部分将过滤结果集。

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

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