【问题标题】:Can the same controller can be used for MVC and WebApi in asp.net 5 mvc 6?asp.net 5 mvc 6中的MVC和WebApi可以使用同一个控制器吗?
【发布时间】:2015-07-27 18:05:45
【问题描述】:

在 MVC 6 中,似乎 MVC 和 WebApi 控制器是相同的。 我有以下代码

[Route("api/[controller]")]
public class TeamController : Controller
{

    public IActionResult Index()
    {
        return View();
    }

    static readonly List<Team> _items = new List<Team>()
    {
        new Team { Id = 1, Name = "First Team" }
    };

    // GET: api/values
    [HttpGet]
    public IEnumerable<Team> Get()
    {
        return _items;
    }
}

我在 Views/Team 文件夹下有 Index.cshtml。 我可以在 localhost:port/api/team 中得到结果,但是 localhost:port/Team/Index 返回 404 错误。

那么如何为 MVC 和 WebApi 使用相同的控制器呢?

【问题讨论】:

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


    【解决方案1】:

    您已将路由属性应用于该类

        [Route("api/[controller]")]
        public class TeamController : Controller
    

    所以它会将该路由部分应用于该控制器中的所有内容。您最好在应用启动时定义自定义路由。

    这是一篇很棒的文章,涵盖了路由,包括混合 MVC/API 控制器: http://stephenwalther.com/archive/2015/02/07/asp-net-5-deep-dive-routing

    【讨论】:

    • 谢谢。这篇文章非常有帮助,现在正在运行。
    【解决方案2】:

    我更改了这样的代码 (blog article linked below)

    [Route("[controller]")]
    public class TeamController : Controller
    {
        [HttpGet("Index")]
        public IActionResult Index()
        {
            return View();
        }
    
        static readonly List<Team> _items = new List<Team>()
        {
            new Team { Id = 1, Name = "First Team" }
        };
    
        // GET: api/values
        [HttpGet]
        public IEnumerable<Team> Get()
        {
            return _items;
        }
    

    将类的 'Route' 属性更改为 [controller],然后将 HttpGet 添加到返回视图的 Index() 方法中。

    现在http://myComputer:52687/Team/Index 返回视图,http://myComputer:52687/Team 返回 JSON 响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2016-08-08
      • 2011-07-15
      • 2012-12-12
      • 2016-03-24
      • 1970-01-01
      • 2013-01-16
      相关资源
      最近更新 更多