ASP.Net 异步 MVC 控制器功能导致 Razor View Engine 错误

ASP.Net Async MVC controller function causes Razor View Engine error

我在使用异步 ASP.Net MVC 控制器方法时遇到问题。我有一个控制器,其中一个视图是 returns 在 HttpGet 到 '/home' 路由上。它同步运行良好,但我想测试我的一些数据库功能,所以我将其更改为异步并添加了一些代码以将模型写入我的数据库。

[RoutePrefix("home")]
public class HomeController : AsyncController
{
    [HttpGet]
    [Route("")]
    public async Task<ActionResult> IndexAsync()
    {
        // DEBUGGING - TEST WRITING USER TO DB
        var user = new UserModel(Guid.NewGuid().ToString(), "test", "test", "test@test.com", "tester");
        await user.WriteToDatabase();
        // DEBUG END

        return View("Index");
    }
}

如果我删除评论之间的线条,视图将正常返回,但是,如果我不删除评论之间的线条,我会收到以下错误:

System.InvalidOperationException

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/Home/Index.aspx

~/Views/Home/Index.ascx

~/Views/Shared/Index.aspx

~/Views/Shared/Index.ascx

~/Views/Home/Index.cshtml

~/Views/Home/Index.vbhtml

~/Views/Shared/Index.cshtml

~/Views/Shared/Index.vbhtml

Description: HTTP 500.Error processing request.

Details: Non-web exception. Exception origin (name of application or object): System.Web.Mvc.

我已验证该视图存在于路径“~/Views/Home/Index.cshtml”中,并且由于页面在同步版本中加载得很好,我知道该视图的语法是正确的。数据库写操作成功,但是因为某些原因找不到视图。

我只是不知道为什么将方法转为异步会突然导致 Razor 视图引擎错误。感谢任何帮助。

AsyncController Class Provided for backward compatibility with ASP.NET MVC 3

虽然执行异步操作,但您应该将操作名称保留为 Index 而不是 IndexAsync。这样你也可以 juet do return View(); 作为你目前正在做的事情。所谓的异步命名约定不适用于操作名称。

你也不应该使用 AsynController,而只是让你的控制器继承自可以处理异步操作的普通 Controller

Remarks: The Controller class in ASP.NET MVC 4 and higher supports the asynchronous patterns.

[RoutePrefix("home")]
public class HomeController : Controller {
    //Matches GET home
    [HttpGet]
    [Route("")]
    public async Task<ActionResult> Index() {
        // DEBUGGING - TEST WRITING USER TO DB
        var user = new UserModel(Guid.NewGuid().ToString(), "test", "test", "test@test.com", "tester");
        await user.WriteToDatabase();
        // DEBUG END

        return View();
    }
}