如何在控制器级别中使用路由

时间:2017-01-03 10:19:21

标签: c# asp.net-web-api asp.net-web-api-routing

这里我试图使用[Route]属性

调用WebApi Controller

为什么@Component public class CustomAuthenticationProvider implements AuthenticationProvider { private Logger log = LoggerFactory.getLogger(CustomAuthenticationProvider.class); @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { log.debug("Authentication: {}.", authentication); ... return new CustomAuthenticationToken(securityToken, authorities, new CustomUser(login, "", true, true, true, true, authorities)); } } 不是已配置的路由 while http://localhost:57997/Hello/Jan/1获取数据

http://localhost:57997/Hello/Jan

2 个答案:

答案 0 :(得分:1)

您的ID应与路线ID

匹配
 [a.Route("Hello/Jan/{id}")]
    public HttpResponseMessage GetDepartmets(int id)

答案 1 :(得分:1)

这是一个最小的完整可验证示例,它基于您使用属性路由控制器的原始帖子。

using a = System.Web.Http;

[a.RoutePrefix("Hello/Jan")] //RoutePrefix used to group common route on controller
public MyController : ApiController {

    //...other code removed for brevity. ie: pro    

    //GET Hello/Jan
    [a.HttpGet]
    [a.Route("")]
    public IHttpActionResult GetDepartmets() {
        var departments = pro.GetDept().ToList();
        return Ok(departments);
    }

    //GET Hello/Jan/1
    [a.HttpGet]
    [a.Route("{id:int}")] //Already have a default route. No need to make this optional
    public IHttpActionResult GetDepartmet(int id) {
         var department = pro.GetDeptById(id);
         if (department != null) {
             return Ok(department);
         }

         return NotFound();    
    }
}

注意:确保在WebApiConfig

中启用了属性路由
//enable attribute routing
config.MapHttpAttributeRoutes();

//...before other convention-based routes.