【问题标题】:Why isn't my ASP.NET API route being called, is my URL not correct?为什么我的 ASP.NET API 路由没有被调用,我的 URL 不正确吗?
【发布时间】:2014-08-05 23:25:13
【问题描述】:

我有一个新的 ASP.NET MVC 5 应用程序。 我在我的控制器文件夹中添加了一个 /api 文件夹,并添加了一个 MVC2 API 控制器。

我的 global.asax 有:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

我的控制器看起来像:

public class UsersController : ApiController
{

    [HttpGet]
    [ActionName("User")] 
    public IToken GetUser()
    {
        return new User();
    }
}

现在我在转到以下位置时收到 404 资源找不到错误:

http://localhost:53323/api/users/user
http://localhost:53323/api/users/getuser

可能是什么问题?

更新

我的 MVC 路由配置:

    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 }
        );
    } 

我的 API 路由配置:

        config.MapHttpAttributeRoutes();

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

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

【问题讨论】:

  • 你能把代码贴在你的 RouteConfig 中吗?
  • 您是否更改了WebApiConfig.cs 文件夹中的App_Start 文件?
  • @Ghukas 见上面我的 webapi 配置。
  • 你是否有一个与stackoverflow.com/questions/10677745/…相同的命名空间下同名的mvc控制器?
  • 这是一个新的解决方案,我还有 1 个其他 MVC 控制器 HomeController

标签: asp.net asp.net-mvc asp.net-web-api


【解决方案1】:

您的Application_Start() 似乎缺少正确的注册。

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration); // This should be above the default route registration.

    RouteConfig.RegisterRoutes(RouteTable.Routes);
    //GlobalConfiguration.Configure(WebApiConfig.Register); // Remove this line.
}

【讨论】:

  • 谢谢,原来这是我的路线顺序。我保留了GlobalConfiguration ... 这条线,但我只是把它放在了 RouteConfig 线的上方。
  • 是的,你是对的,我也刚查过。只有顺序才有意义。
【解决方案2】:

尝试在您的控制器和操作方法上使用attribute routing

示例

[RoutePrefix("api/users")]
public class UsersController : ApiController
{

    [HttpGet]
    [Route("user")]
    public IToken GetUser()
    {
        return new User();
    }
}

【讨论】:

    猜你喜欢
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 2013-11-26
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    相关资源
    最近更新 更多