文章目录
- 1、添加路由
- 2、编写接口
- 3、多路由说明
- 4、DEMO实例下载
提供的api地址都需要满足一定规则,
asp.net mvc 默认的路由格式固定,不能满足,所以需要自己添加自定义路由
1、添加路由
在“RouteConfig.cs”类中添加自定义路由配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace VideoMonitorPlatform
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"api",
"api/v1/{controller}/{action}",
new { controller = "Home", action = "test" }
);
}
}
}
2、编写接口
在“MonitorController”类中添加POST接口,具体如下:
// POST: /api/v1/Monitor/StartCapture
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> StartCapture()
{
System.Diagnostics.Debug.WriteLine("====================Setting START===================");
Object result;
string cronTime = "*/10 * * * * ?";
Dictionary<string, object> map = new Dictionary<string, object>();
map.Add("channel", 0);
map.Add("quaility", 6);
map.Add("imageSize", 2);
string jobName = Constants.CAPTURE_JOB_KEY_PREFIX + "cameraIds";
System.Diagnostics.Debug.WriteLine("创建名称为【" + jobName + "】,表达式为【" + cronTime + "】的定时任务");
await QuartzUtil.AddJob<CaptureJob>(jobName, cronTime, map);
result = new
{
error = "SUCCESS",
error_info = "调用成功"
};
string jsonstr = JsonConvert.SerializeObject(result);
System.Diagnostics.Debug.WriteLine("====================Setting END===================");
return Content(jsonstr);
}
3、多路由说明
我们在路由器中添加了自定义路由,原有默认路由也进行了保留,所以此方法可以通过两个地址访问(对的,定义的不同路由都会响应同一个方法),如本例中的方法响应下面两个地址(POST方式):
http://127.0.0.1:50195/Monitor/StartCapturehttp://127.0.0.1:50195/api/v1/Monitor/StartCapture