I have created a WEB API
using MySQL
Database. The API works as expected for now. I sent a meter serial number and a date time parameter and then GET the expected result. Below is my controller
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);
}
}
Below is my WebApiConfig
file
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}$" }
);
The URL is http://localhost:14909/api/meters/GetByMsn/002999000171/2017-10-10T10:08:20
The response I GET is
[{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:04:39",
"Signal_Strength": "20"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:06:35",
"Signal_Strength": "19"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:08:31",
"Signal_Strength": "20"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:10:27",
"Signal_Strength": "20"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:12:23",
"Signal_Strength": "20"
}]
This all scenario works when a single serial number
is passed. But at client side there would be more than one different serial numbers. For this I had to make my method to work both for one and more than one serial numbers provided the date time will be the same for all.
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.
I have searched for it but most of the times I have found the static method again and again. But this solution looks some what helpful but again I don't know whether it will work or not.
Any help would be highly appreciated.