HttpGet在Mvc core 2.0中返回404

时间:2018-01-22 14:57:05

标签: c# asp.net-core asp.net-core-mvc-2.0

public class SurveyController : Controller
{
    public IActionResult Index()
    {
        var surveys = new List<int>{1};
        return View(Surveys);
    }

    [HttpGet("conditions")]
    public IActionResult GetConditions()
    {
        List<int> Conditions = new List<int{1};
        return View("Conditions",Conditions);
    }
}

现在视图在

Views/Survey/Index.cshtml

Views/Survey/Conditions.cshtml

路线Survey/conditions正在返回404

有人有任何想法吗?

我的startup.cs是 -

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });   
}

2 个答案:

答案 0 :(得分:4)

您对该操作的属性:

[HttpGet("conditions")]

指定您希望网址为http://whatever/conditions。相反,你应该使用:

[HttpGet("/survey/conditions")]

如果您希望以更好的粒度控制路由,则应使用Route属性。例如:

[Route("[controller]")] //Set the prefix for subsequent route attributes
public class SurveyController : Controller
{
    [Route("conditions")]
    public IActionResult GetConditions()
    {
        List<int> Conditions = new List<int{1};
        return View("Conditions",Conditions);
    }
}

参考Routing to Controller Actions

答案 1 :(得分:1)

试试这个:

public class SurveyController : Controller
{
    public IActionResult Index()
    {
        var surveys = new List<int>{1};
        return View(Surveys);
    }

    [HttpGet("conditions")]
    [Route("Survey/conditions")]
    public IActionResult GetConditions()
    {
        List<int> Conditions = new List<int{1};
        return View();
    }
}

或更改控制器中的功能名称:

public class SurveyController : Controller
{
    public IActionResult Index()
    {
        var surveys = new List<int>{1};
        return View(Surveys);
    }

    [HttpGet("conditions")]
    public IActionResult conditions()
    {
        List<int> Conditions = new List<int{1};
        return View();
    }
}

或在浏览器中的浏览器路径中写下函数名称:

路线=&#39; Survey / GetConditions&#39;