asp.net核心中的ViewEngineCollection替代方案?

时间:2018-05-17 12:56:15

标签: asp.net-core .net-core

我正在将Asp.Net MVC应用程序迁移到Asp.Net Core。

我遇到了这行代码:

if (this.ViewEngineCollection.FindView(this.ControllerContext, viewPath, null).View != null)
{
    return this.View(viewPath);
}

我无法找到在asp.net核心中执行ViewEngineCollection.FindView的替代方法。

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用依赖注入注入IRazorViewEngine实例并调用FindView。您必须使用此界面传入ActionContext实例而不是ControllerContext

答案 1 :(得分:0)

我得到了解决方案,感谢Henk Mollema

  • 控制器类
public class NewsController : Controller
{
    private readonly IRazorViewEngine _razorViewEngine;
    private readonly IActionContextAccessor _actionContextAccessor;

    public NewsController(IRazorViewEngine razorViewEngine, IActionContextAccessor actionContextAccessor)
    {
        _razorViewEngine = razorViewEngine;
        _actionContextAccessor = actionContextAccessor;
    }

    public IActionResult Index()
    {   
        var gotView = _razorViewEngine.GetView(string.Empty, viewName, true);

        if (gotView.Success)   //gets true
        {
            return View(viewName);
        }
        return NotFound();
    }
}

* startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    services.AddMvc();
}

同样可以在GitHub上找到here