【问题标题】:MVC Controller not being reached in Web API ProjectWeb API 项目中未达到 MVC 控制器
【发布时间】:2016-04-07 16:04:01
【问题描述】:

我有一个需要返回 MVC 样式视图的 Web Api 项目。我已经制作了我的 MVC 控制器

public class MVCController: Controller
{
    [HttpGet]
    [Route("api/mvc/test")]
    public ActionResult test()
    {
        return View();
    }
}

但是,当我尝试从 Web 访问此控制器时,我似乎无法访问控制器。我收到以下错误:

{"Message":"未找到与请求 URI 'http://localhost/foo/api/mvc/test'匹配的 HTTP 资源。","MessageDetail":"未找到与名为 'mvc' 的控制器匹配的类型。"}

在google上搜索后,人们似乎告诉我将webapiconfig中的路由属性更改为

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

但我似乎仍然没有运气。如果我将我的控制器更改为 webapi 控制器,那么

public class MVCController: ApiController
{
    [HttpGet]
    [Route("api/mvc/test")]
    public IHttpActionResult test()
    {
        return Ok();
    }
}

我可以联系到控制器。如果有人能给我一些关于正在发生的事情的见解,我将不胜感激。

更新 阅读下面的回复后,我将控制器更新为如下所示:

public class MVCController: Controller
{
    [HttpGet]
    public ActionResult test()
    {
        return View();
    }
}

但是,localhost/MVCController/test 似乎仍然给我一个 404 错误,并且控制器没有被击中。顺便说一句,对不起我的新手。

【问题讨论】:

  • 并且 api 只是在测试,因为我认为将 mvc 控制器格式化为与 web-api 相同的方式会有所帮助。这是一个绝望的措施LOOL

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


【解决方案1】:

我敢打赌,您有一个名为 WebApiConfig.cs 的文件,其中包含此代码。

public static class WebApiConfig
{
    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 }
        );
    }
}

这是为 Web api 控制器定义路由模式的地方。因此,任何带有 api/something 的请求都将被视为对 Web api 端点的请求,因为您必须在为 mvc 控制器注册路由之前调用 WebApiConfig.Register 调用。注册路由的顺序真的很重要。

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);   // first one    
    RouteConfig.RegisterRoutes(RouteTable.Routes);    //second one

}

由于注册的顺序很重要,当一个请求带有api/something时,它将与web apis的路由注册匹配,框架将尝试寻找匹配的web api控制器。s

如果您交换调用路由注册方法的顺序,您的请求将起作用。但是当您尝试访问 Web api 控制器时,这可能会影响其他部分。

顺便说一句,您确定要在 MVC 控制器的路由模式中使用 api/ 吗?除非您真的想要一些与正常约定不同的 url 模式(*controllername/action*),否则只需删除它自己的 Route 属性。使用默认路由定义,它将适用于yourSite/mvc/test 请求。

【讨论】:

  • 你说得对,我确实有 config.MapHttpAttributeRoutes();.
  • 有解决办法去掉吗?
  • 只需从你的 mvc 控制器的路由中删除 api。
  • 我似乎仍然无法接触到控制器。我现在收到 HTTP 错误 404.0 - Not Found Error 的提示
  • 为什么你还有路由属性?您的路线似乎与正常约定相同(导致麻烦的 api 部分除外)。请参阅我的更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
相关资源
最近更新 更多