API 中的可选参数

Optional Parameter in API

我是 运行 一个使用 C# 的 MVC 中的 API 控制器,我想在 ...

之后从 Xamarin 中的应用程序使用此 Web 服务

在控制器的 GET 方法中,我需要捕获参数 ROL 或参数 Patent .... 或者两者一起

我只同时使用这两个参数!!进入ROL和Patent给我相应的市级专利...

我想要的是让用户输入 1(ROL 或专利)或 2 个参数(角色和专利)并进行相同的工作

我已经尝试过 if ...但我没有成功 对我有帮助吗?

When I consult 2 parameters When I consult 1 parameters (ROL o Patente)

  // GET: api/PatenteMunicipalsAPI/ROL/Patente
        [ResponseType(typeof(PatenteMunicipal))]
        public IHttpActionResult GetPatenteMunicipal(string id, string param2)
        {

            var patenteMunicipal = db.PatenteMunicipals.ToList().
                Where(u => u.ROL == id && u.Patente == param2).
                FirstOrDefault();                    

            return Ok(patenteMunicipal);
        }

您可以通过两种方式执行此操作。第一种方法是利用 Linq 在您尝试访问结果(例如 ToList()、FirstOrDefault() 等)之前不会实际执行的事实,因此您可以按如下方式分段构建查询;

//Make sure we have at least one parameter so we don't return all table rows
if(string.IsNullOrEmpty(id) && string.IsNullOrEmpty(param2))
    throw new ArgumentNullException("At least one parameter must be provided");

//Create the base query but don't execute
var query = from pm in Db.PatenteMunicipals select pm;

//Add the where clause for id if provided
if(!string.IsNullOrEmpty(id)
      query = query.Where(x => x.ROL == id);

//Add the where clause for param2 is provided
if(!string.IsNullOrEmpty(param2)
      query = query.Where(x => x.Patente == param2);

//Now force the query to execute and return results
var result = query.FirstOrDefault();
return Ok(result);

如果您的要求变得更加复杂,另一种选择是使用 System.Linq.Dynamic,它可以作为 Nuget 包使用,它允许您将 where 子句创建为字符串。然后,您可以在执行 linq 语句之前在代码中构建 where 子句字符串,但这对于您在这里需要的东西来说可能有点过分了。

希望对您有所帮助。