Last active
October 25, 2019 20:32
-
-
Save ygrenier/4e46b5de3e4a77ea62fe5f0d6488fa2a to your computer and use it in GitHub Desktop.
ASP.NET Core - Controller extension to test if a view exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc.ViewEngines; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace Microsoft.AspNetCore.Mvc | |
{ | |
/// <summary> | |
/// Controller extensions | |
/// </summary> | |
public static class ControllerExtensions | |
{ | |
/// <summary> | |
/// Test if a view exists | |
/// </summary> | |
public static bool ViewExists(this ControllerBase controller, string name) | |
{ | |
var services = controller.HttpContext.RequestServices; | |
var viewEngine = services.GetRequiredService<ICompositeViewEngine>(); | |
var result = viewEngine.GetView(null, name, true); | |
if (!result.Success) | |
result = viewEngine.FindView(controller.ControllerContext, name, true); | |
return result.Success; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a Controller extension to test if a view exists.