为什么我的请求走错了路线?

Why Is My Request Going to the Wrong Route?

我的请求有效,但它的路线不正确。我不明白为什么。

我在启动项目时收到“200 ok”的响应,但它的路线错误。

我想要路线 http://localhost:4047/api/[controller]http://localhost:4047/ 有效!没有我在哪里指定这条路线。

Here is the controller.

[EnableCors(origins: "*", headers: "*", methods: "*")]
[Route("api/[controller]")]
public class MenuController : ApiController
{
    private IMenuRepo xMenuRepo;
    public MenuController(IMenuRepo iopt)
    {
        xMenuRepo = iopt;
    }
    [HttpGet]
    [Route("")]
    public HttpResponseMessage GetOk()
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

Here is the WebApiConfig

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    config.EnableCors();
    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}"
    );
}

Here is the Route Config

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "api/{controller}",
        defaults: new { controller = "Home" }
    );
}

据我所知,api/Menu 应该是正确的路线。

是的,您正在指定路线

//GET /
[HttpGet]
[Route("")]
public HttpResponseMessage GetOk()
{
    return new HttpResponseMessage(HttpStatusCode.OK);
}

controller需要路由前缀,而example只是指定一个controller路由。

更改为:

[EnableCors(origins: "*", headers: "*", methods: "*")]
[RoutePrefix("api/Menu")]
public class MenuController : ApiController {
    private IMenuRepo xMenuRepo;
    public MenuController(IMenuRepo iopt) {
        xMenuRepo = iopt;
    }

    //GET api/Menu
    [HttpGet]
    [Route("")]
    public HttpResponseMessage GetOk() {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

OP [Route("api/[controller]")] 中的语法适用于 asp.net-core

来源:Attribute Routing in ASP.NET Web API 2