这是我的web api控制器:
[HttpGet]
public HttpResponseMessage SensorData(string id)
{
try
{
Responds data = AccessRemote.GetDataFromDevice(id);
DataResponds dataResponds = data.ReturnDatRequest[0];
return Request.CreateResponse(HttpStatusCode.OK, dataResponds);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Forbidden, ex.Message);
}
}
[HttpGet]
public HttpResponseMessage GetLogs(string GetRecordsById)
{
try
{
IQueryable<SensorInfo> data = sensorResultsRepos.Get();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, data);
return response;
}
catch (Exception)
{
throw;
}
}
这是我的资源angularjs定义:
(function () {
"use strict";
angular.module("sensorManagement").factory("SensorResource",
["$resource",
SensorResource])
function SensorResource($resource) {
return $resource("http://localhost:1234/api/SomeData/:id");
}
}());
这是web api路线:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
"DefaultApiSensor",
"api/{controller}/{id}",
new { controller = "Sensor", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
在某些时候,我需要访问 SensorData 操作或 GetLogs 操作 使用SensorResource服务。
既是HTTP GET又都有一个参数的问题。
如果一个控制器中的传感器数据和 GetLogs ,那么如何调用获取类型?
提前谢谢!
答案 0 :(得分:0)
您可以使用属性路由轻松解决此问题。有关此主题的更多信息,请参阅this link。
[HttpGet]
[Route("sensor/{id}")]
public HttpResponseMessage SensorData(string id)
{
try
{
Responds data = AccessRemote.GetDataFromDevice(id);
DataResponds dataResponds = data.ReturnDatRequest[0];
return Request.CreateResponse(HttpStatusCode.OK, dataResponds);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Forbidden, ex.Message);
}
}
[HttpGet]
[Route("logs/{GetRecordsById}")]
public HttpResponseMessage GetLogs(string GetRecordsById)
{
try
{
IQueryable<SensorInfo> data = sensorResultsRepos.Get();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, data);
return response;
}
catch (Exception)
{
throw;
}
}