Skip to content

Instantly share code, notes, and snippets.

@ygrenier
Last active October 25, 2019 20:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ygrenier/4e46b5de3e4a77ea62fe5f0d6488fa2a to your computer and use it in GitHub Desktop.
Save ygrenier/4e46b5de3e4a77ea62fe5f0d6488fa2a to your computer and use it in GitHub Desktop.
ASP.NET Core - Controller extension to test if a view exists
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;
}
}
}
@ygrenier
Copy link
Author

This is a Controller extension to test if a view exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment