无法使 web api 属性路由正常工作

Can't get web api attribute routing to work

正在尝试调用此方法:

    [HttpGet]
    [Route("teacher/{teacherId}/student")]
    public IEnumerable<StudentDTO> GetByStudentByTeach(int id)
    {

网络api配置:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

我运行服务并在浏览器中调用它: http://localhost:17305/api/teacher/164/student

在浏览器中它 return 是 404。我在 fiddler 中试过,它 return 是 401。我猜 401 是实际问题,但这是否意味着路由有效还有其他问题吗?我正在使用 windows auth.

编辑:不,我可以使用通常的 api/teacher 调用 Get 方法到 return 教师列表。所以我能够 return 数据,我只是无法使用这个自定义方法。

您需要删除 /api/ 所以尝试 http://localhost:17305/teacher/164/student

api/ 在 maphttproute 中定义,但在您的路由属性中不存在。

此外,更改方法的参数名称:GetByStudentByTeach(int teacherId)