WebApi Http Get在HomeController中不起作用

时间:2018-01-04 10:33:05

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

目前我正在使用Asp.Net MVC Core学习Web Apis。当我浏览'localhost \ home \ Test'时,我尝试了以下简单的代码来获取返回。但是404错误出来了。有什么我想念的吗?

namespace JB.Controllers
{
    public class HomeController : Controller
    {
        private readonly IConfiguration _configuration;
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }


        [AllowAnonymous]
        [HttpGet("Test")]
        public IEnumerable<string> Test()
        {
            return new string[] { "Tvalue1", "Tvalue2" };
        }

1 个答案:

答案 0 :(得分:1)

路线模板与所需路线不匹配。

您的期望是基于基于约定和属性路由的混合。

当前路线模板将根据操作中的localhost/Test映射到Route

在行动

上更新路线模板
public class HomeController : Controller {

    //...code removed for brevity

    [AllowAnonymous]
    [HttpGet("home/Test")] //Maps GET home/test
    public IActionResult Test()  {
        var model = new string[] { "Tvalue1", "Tvalue2" };
        return Ok(model);
    }
}

或在控制器上应用路由前缀

[Route("[controller]")]
public class HomeController : Controller {

    //...code removed for brevity

    [AllowAnonymous]
    [HttpGet("Test")] //Maps GET home/test
    public IActionResult Test()  {
        var model = new string[] { "Tvalue1", "Tvalue2" };
        return Ok(model);
    }
}

参考Routing to Controller Actions