根据WEBAPI的路由规则,在实际项目当中有二种用法,
一:webAPI.Config里面为
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
控制器里面加上【HttpGet,HttpPOST】认证,并将接口使用路由暴露出来,写法有两种
(1)在控制器上面加上路由前缀,action之前加上action名字从而将整个路由暴露出来,方便前端调用
[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
// GET api/values
[HttpGet]
[Route("testLog")]
public IEnumerable<string> testLog()
{
LogHelper.WriteLog("hello can you hear me~");
return new string[] { "value1", "value2" };
}
(2)直接在action之前加上整个路由路径从而将整个路由暴露出来
public class ValuesController : ApiController
{
// GET api/values
[HttpGet]
[Route("api/Values/testLog")]
public IEnumerable<string> testLog()
{
LogHelper.WriteLog("hello can you hear me~");
return new string[] { "value1", "value2" };
}
二:webAPI.Config里面为
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
控制器里面加上【HttpGet,HttpPOST】认证, 不需要使用路由暴露接口
[HttpGet]
public IEnumerable<string> testLog()
{
LogHelper.WriteLog("hello can you hear me~");
return new string[] { "value1", "value2" };
}
两种情况,如果不使用【httpPost】【httpGet】,后台会根据前台的请求类型匹配控制器的action,如get请求,不管前台访问哪个接口,后台均匹配以Get开头的控制器action