ASP.NET Web API專案自定義介面路由和HTTP請求方式
阿新 • • 發佈:2019-02-03
在實際編寫介面的過程中難免有一些特殊的介面,比如動態引數介面,以“JTT1078-2016道路運輸車輛衛星定位系統視訊通訊協議(掃描版)”中的HTTP URL服務要求為例,截圖如下:
定義API介面和請求方式
介面定義要滿足需求,這裡通過四種HTTP 請求方式。using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace RTVSApi.Controllers { /// <summary> /// 政府音視訊監管平臺請求介面服務API /// </summary> public class MonitorController : ApiController { /// <summary> /// 政府音視訊監管平臺傳送音視訊連線指令 /// </summary> /// <param name="param">引數字串:[車牌號碼].[車牌顏色].[邏輯通道號].[音視訊標誌].[時效口令]</param> /// <returns></returns> [Route("{param}")] [HttpGet] [HttpPost] [HttpPut] [HttpDelete] public void RealTimeConnection(string param) { if (string.IsNullOrEmpty(param)) return; string[] paramArray = param.Split('.'); // 引數須滿足固定長度 if (paramArray.Length==5) { string CarNumber = paramArray[0]; string CarPlateColor = paramArray[1]; string Channel = paramArray[2]; string AVType = paramArray[3]; string TimedPassword = paramArray[4]; } } } }
配置指定介面的路由方式
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace RTVSApi { 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( name: "Monitor", url: "{param}", defaults: new { controller = "Monitor", action = "RealTimeConnection", id = UrlParameter.Optional } ); } } }
執行專案檢視定好的介面是否可行
檢視介面目錄列表:以GET請求方式為例,我們檢視引數情況:
經過除錯,請求可以進去,但是加了'.'的字元感覺有點問題,總之大的方向是對的。
AcceptVerbs註解實現HTTP多請求方式
[AcceptVerbs("Get", "Post")] //用AcceptVerbs標識即可 public List<PUB_HqewIndexResult> GetSalesRankByHqewIndex() { List<PUB_HqewIndexResult> resultList = new List<PUB_HqewIndexResult>(); DMSParam dmsParam = new DMSParam(); List<PUB_Stock> stockList = new List<PUB_Stock>(); IResult stockResult = ExecuteDmsParam(dmsParam, new PUB_HqewIndex(), "PUB.PUB_HqewIndexBLL", "GetSalesRankByHqewIndex"); if (stockResult.Complete == DMSComplete.Succeed) { if (stockResult != null && stockResult.Result != null) { resultList = (List<PUB_HqewIndexResult>)stockResult.Result; } } return resultList; }