linq – 将多个参数传递给Web API GET方法

我使用MysqL数据库创建了一个WEB API. API现在按预期工作.我发送了一个仪表序列号和一个日期时间参数,然后获得了预期的结果.下面是我的控制器
public MDCEntities medEntitites = new MDCEntities();
public HttpResponseMessage GetByMsn(string msn,DateTime dt)
    {          
        try
        {
            var before = dt.AddMinutes(-5);
            var after = dt.AddMinutes(5);

            var result = medEntitites.tj_xhqd
                         .Where(m =>
                         m.zdjh == msn &&
                         m.sjsj >= before &&
                         m.sjsj <= after).Select(m => new { MSN = m.zdjh,DateTime = m.sjsj,Signal_Strength = m.xhqd }).distinct();


            return Request.CreateResponse(HttpStatusCode.Found,result);
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound,ex);
        }
    }

下面是我的WebApiConfig文件

config.Routes.MapHttpRoute(
       name: "GetByMsn",routeTemplate: "api/{controller}/{action}/{msn}/{dt}",defaults: null,constraints: new { msn = @"^[0-9]+$",dt = @"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$" }
       );

网址为http:// localhost:14909 / api / meters / GetByMsn / 002999000171 / 2017-10-10T10:08:20

我得到的回应是

[{
    "MSN": "002999000171","DateTime": "2017-10-10T10:04:39","Signal_Strength": "20"
},{
    "MSN": "002999000171","DateTime": "2017-10-10T10:06:35","Signal_Strength": "19"
},"DateTime": "2017-10-10T10:08:31","DateTime": "2017-10-10T10:10:27","DateTime": "2017-10-10T10:12:23","Signal_Strength": "20"
}]

当传递单个序列号时,此所有方案都有效.但在客户端,会有不止一个不同的序列号.为此,我必须让我的方法同时为一个和多个序列号工作,前提是所有人的日期时间都相同.

One solution is to create a new method a pass the multiple serial number strings,but this will not help because the number of serial numbers are dynamic i.e. they may be one,two to 100's. So setting a hard coded method won't be a solution.

我已经搜索过了,但大多数时候我一次又一次地找到静态方法.但是这个solution看起来有些有用,但我不知道它是否会起作用.

任何帮助将受到高度赞赏.

解决方法

您可以将自定义模型传递给操作方法,但我建议不要为您执行GET任务,因为GET没有正文.

而是使用SEARCH动词并将序列号和日期列表放在正文中的自定义模型中.

public class MeterSearchModel 
{
   public List<string> Serials {get;set;}
   public DateTime Date {get;set;}  
}

在.NET Core 2中,您的控制器会有类似的东西 –

[AcceptVerbs("SEARCH")]
public async Task<IActionResult> Search([FromBody] MeterSearchModel model)
{
    //..perform search 
}

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些