using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.Rendering; namespace Util.Samples.RazorPageExtensions { /// /// 相对路径视图位置扩展器 /// public class RelativePathViewLocationExpander : IViewLocationExpander { /// /// 填充值 /// public void PopulateValues( ViewLocationExpanderContext context ) { context.Values["customviewlocation"] = nameof( RelativePathViewLocationExpander ); } /// /// 扩展视图位置 /// public IEnumerable ExpandViewLocations( ViewLocationExpanderContext context, IEnumerable viewLocations ) { if( !context.ViewName.StartsWith( "~" ) && context.ActionContext is ViewContext viewContext ) { var executingFilePaths = viewContext.ExecutingFilePath.Split( '/' ); var result = $"{JoinUrl( executingFilePaths )}{context.ViewName}.cshtml"; return new[] { result }; } return viewLocations; } /// /// 拼接Url /// /// 路径 private string JoinUrl( string[] paths ) { var result = new StringBuilder(); for( var i = 0; i < paths.Length - 1; i++ ) { result.Append( paths[i] ); result.Append( "/" ); } return result.ToString(); } } }