How to write a function that can be available in all Razor views? - razor

I'm trying to write a function that can bring a language resource from database in MVC 5 and Razor,
I want it to be very simple to use, for example, the following function should just get some text:
#T("ResourceType", "ResourceName")
I don't want to use #this. - just the the function name...
I saw some posts about it mentioning the line below, but still trying to understand how to do it
public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
Any help will be greatly appreciated.
Thanks in advance.

I finally found a way to do it, inspired by the NopCommerce project, see the code below.
The code can be used in any Razor (cshtml) view like this:
<h1>#T("StringNameToGet")</h1>
Also, note that pageBaseType needs to be updated with the correct new namespace,
this is the web.config in the Views folder - not the main one, should look like this:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="MyNameSpace.Web.Extensions.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="APE.Web" />
</namespaces>
</pages>
The code:
namespace MyNameSpace.Web.Extensions
{
public delegate LocalizedString Localizer(string text, params object[] args);
public abstract class WebViewPage : WebViewPage<dynamic>
{
}
/// <summary>
/// Update the pages element /views/web.config to reflect the
/// pageBaseType="MyNameSpace.Web.Extensions.WebViewPage"
/// </summary>
/// <typeparam name="TModel"></typeparam>
public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
{
private Localizer _localizer;
/// <summary>
/// Get a localized resources
/// </summary>
public Localizer T
{
get
{
if (_localizer == null)
{
//null localizer
//_localizer = (format, args) => new LocalizedString((args == null || args.Length == 0) ? format : string.Format(format, args));
//default localizer
_localizer = (format, args) =>
{
var resFormat = SampleGetResource(format);
if (string.IsNullOrEmpty(resFormat))
{
return new LocalizedString(format);
}
return
new LocalizedString((args == null || args.Length == 0)
? resFormat
: string.Format(resFormat, args));
};
}
return _localizer;
}
}
public string SampleGetResource(string resourceKey)
{
const string resourceValue = "Get resource value based on resourceKey";
return resourceValue;
}
}
public class LocalizedString : System.MarshalByRefObject, System.Web.IHtmlString
{
private readonly string _localized;
private readonly string _scope;
private readonly string _textHint;
private readonly object[] _args;
public LocalizedString(string localized)
{
_localized = localized;
}
public LocalizedString(string localized, string scope, string textHint, object[] args)
{
_localized = localized;
_scope = scope;
_textHint = textHint;
_args = args;
}
public static LocalizedString TextOrDefault(string text, LocalizedString defaultValue)
{
if (string.IsNullOrEmpty(text))
return defaultValue;
return new LocalizedString(text);
}
public string Scope
{
get { return _scope; }
}
public string TextHint
{
get { return _textHint; }
}
public object[] Args
{
get { return _args; }
}
public string Text
{
get { return _localized; }
}
public override string ToString()
{
return _localized;
}
public string ToHtmlString()
{
return _localized;
}
public override int GetHashCode()
{
var hashCode = 0;
if (_localized != null)
hashCode ^= _localized.GetHashCode();
return hashCode;
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
return false;
var that = (LocalizedString)obj;
return string.Equals(_localized, that._localized);
}
}
}

Related

Why is this <p:selectManyMenu> not working? (getAllDatasourceGroups() is not even called once)

My problem is about this primefaces tag:
<p:selectManyCheckbox id="datasourceGroup" value="#{sessionBean.datasourceGroups}" converter="datasourceGroupConverter">
<f:selectItems value="#{sesionBean.getAllDatasourceGroups()}" var="group" itemLabel="#{group.toString()}" itemValue="#{group}" />
</p:selectManyCheckbox>
It does not render any visible output (checkboxes) at all. From logging output i know that the 'sessionBean.getAllDatasourceGroups()' method is not even called once during page refresh. only the 'sessionBean.getDatasourcegroups()' getter for the 'datasourceGroups' property is called once.
And i can't figure out what the problem is. I have very similar usecases of <p:selectManyMenu> and <p:selectOneMenu> on the same page and they work fine. So i have a basic understanding of how this works...or so i thought :-)
here are the other relevant parts of the code for reference:
SessionBean:
#ManagedBean
#SessionScoped
public class SessionBean implements Serializable {
private List<DatasourceGroup> datasourceGroups = new ArrayList<>();
public List<DatasourceGroup> getDatasourceGroups() {
return datasourceGroups;
}
public void setDatasourceGroups(List<DatasourceGroup> datasourceGroups) {
this.datasourceGroups = datasourceGroups;
}
public List<DatasourceGroup> getAllDatasourceGroups() {
List<DatasourceGroup> list = Arrays.asList(DatasourceGroup.values());
return list;
}
}
DatasourceGroup Enum:
public enum DatasourceGroup {
KUNDEN (Permission.ZugriffKunden),
INKASSO (Permission.ZugriffInkasso),
INTERESSENTEN (Permission.ZugriffInteressenten),
WARN (Permission.ZugriffWarnadressen);
private Permission permissionNeeded;
DatasourceGroup(Permission permission) {
this.permissionNeeded=permission;
}
public Permission getPermissionNeeded() {
return permissionNeeded;
}
}
And the DatasourceGroupConverter:
#FacesConverter("datasourceGroupConverter")
public class DatasourceGroupConverter implements Converter {
#Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if (Toolbox.isNullOrEmpty(value))
return null;
try {
return DatasourceGroup.valueOf(value);
} catch (IllegalArgumentException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error:",
"'" + value + "' is not a valid datasource group name"));
}
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object object) {
if(object != null && object instanceof DatasourceGroup) {
return ((DatasourceGroup)object).toString();
}
return null;
}
}
I'm using primefaces 6.0 by the way.

mvvmcross keep program settings using file plugin and json serialize/deserialize

I'm trying to use the fileplugin and json serializer to do this.
I have the following DcsSetup class, in the core project.
For now I'm working with droid. I can't seem to save the file. The json serialize is ok. The WriteFile seems ok, but next time I try to read the file using TryReadTextFile it fails.
I can't find the file on the device, so I think the WriteFile stuff is wrong.
What is the correct way to save and read my Settings class on Android?
public class DcsSetup
{
public class Settings
{
//Server
public string Server;
public int Port;
public int Device;
public string EncodingFromClient;
public string EncodingToClient;
public int FontCorrectionPixelsWidth; //Pixels to add or subtract i Y dimension to get the right font size
public int FontCorrectionPixelsHeight; //Pixels to add or subtract i Y dimension to get the right font size
public float XPct;//Pct to add to vertical placement of textBox and Buttons.
public float YPct;//Pct to add to horisontal placement of textBox and Buttons.
public float SizePct;//Pct to add to horisontal size of textBox and Buttons.
public bool FullScreen;
public bool DontSleep;
//Diverse
public bool AutoSendEnter;
}
public Settings Setting;
public DcsSetup()
{
var setupFound=true;
var fileService = Mvx.Resolve<IMvxFileStore>();
var jsonConvert = Mvx.Resolve<IMvxJsonConverter>();
var path = fileService.PathCombine("Setting", "Settings.txt");
Setting = new Settings();
try {
string settingFile;
if (fileService.TryReadTextFile(path, out settingFile)){
Setting = jsonConvert.DeserializeObject<Settings>(settingFile);
} else{
setupFound = false;
}
}
catch(Exception e) {
AppTrace.Error("Failed to read settings: {0}", e.Message);
setupFound=false;
}
if(setupFound==false){
Setting.Server = "192.168.1.100";
Setting.Port = 1650;
Setting.Device = 1;
Setting.EncodingFromClient = "CP1252";
Setting.EncodingToClient = "CP1252";
Setting.FontCorrectionPixelsWidth = 0;
Setting.FontCorrectionPixelsHeight = 0;
Setting.XPct = 97.0f;
Setting.YPct = 100.0f;
Setting.SizePct = 98.0f;
Setting.FullScreen = false;
Setting.DontSleep = true;
Setting.AutoSendEnter = true;
try {
//json
var json = jsonConvert.SerializeObject(Setting);
fileService.EnsureFolderExists("Setting");
fileService.WriteFile(path, json);
}
catch (Exception e) {
AppTrace.Error("Failed to save settings: {0}", e.Message);
}
}
}
}
}
I just created a project in VS2012 using the 3.1.1-beta2 packages for MvvmCross
I then added the File and Json plugin packages
I changed the core FirstViewModel to:
public class FirstViewModel
: MvxViewModel
{
private readonly IMvxFileStore _fileStore;
private readonly IMvxJsonConverter _jsonConverter;
private readonly string _filePath;
public class ToStore
{
public string Foo { get; set; }
}
public ICommand SaveCommand
{
get
{
return new MvxCommand(() =>
{
var toStore = new ToStore() {Foo = Hello};
var json = _jsonConverter.SerializeObject(toStore);
_fileStore.WriteFile(_filePath, json);
});
}
}
public ICommand LoadCommand
{
get
{
return new MvxCommand(() =>
{
string txt;
if (_fileStore.TryReadTextFile(_filePath, out txt))
{
Mvx.Trace("Loaded {0}", txt);
var stored = _jsonConverter.DeserializeObject<ToStore>(txt);
Hello = stored.Foo;
}
});
}
}
private string _hello = "Hello MvvmCross";
public FirstViewModel(IMvxFileStore fileStore, IMvxJsonConverter jsonConverter)
{
_fileStore = fileStore;
_jsonConverter = jsonConverter;
_filePath = _fileStore.PathCombine("SubDir", "MyFile.txt");
_fileStore.EnsureFolderExists("SubDir");
}
public string Hello
{
get { return _hello; }
set { _hello = value; RaisePropertyChanged(() => Hello); }
}
}
I called this from a test Android UI:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
local:MvxBind="Text Hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
local:MvxBind="Text Hello"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Load"
local:MvxBind="Click LoadCommand"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Save"
local:MvxBind="Click SaveCommand"
/>
</LinearLayout>
This seemed to work OK - it saved and loaded the JSON fine within and between test runs.
Based on this, my only guess is whether you are redeploying the app between runs - if you do this and you don't have MonoDroid's Preserve application data/cache on device between deploys checked, then you won't see the settings preserved.

ConfigurationSection with nested ConfigurationElementCollections

Hopefully, I can present this problem to the brain trust of this site and someone will see my mistake.
I am working on a project where email text needs to be "mail merged" with information found in the properties of various internal classes. A typical symbol found in the email text might look like "{member name}, {mobile phone}, etc."
I would like to define the symbols and the classes they are found in using a ConfigurationSection in web.config. Here is my proposed configuration section:
<EmailSymbols>
<SymbolClasses>
<SymbolClass name="OHMember">
<Symbol name="Member Name" template="{0} {1}">
<add index="0" value="SMFirstName" />
<add index="1" value="SMLastName" />
</Symbol>
<Symbol name="Phone" template="{0}">
<add index="0" value="SMPhone" />
</Symbol>
</SymbolClass>
<SymbolClass name="Form">
<Symbol name="Contact Name" dataname="ContactName" />
</SymbolClass>
</SymbolClasses>
</EmailSymbols>
...and the code that I am trying to parse it with:
public class EmailSymbols : ConfigurationSection {
[ConfigurationProperty("SymbolClasses", IsRequired = true)]
public SymbolClassCollection SymbolClasses {
get {
return this["SymbolClasses"] as SymbolClassCollection;
}
}
}
[ConfigurationCollection(typeof(SymbolClass), AddItemName = "SymbolClass")]
public class SymbolClassCollection : ConfigurationElementCollection {
protected override ConfigurationElement CreateNewElement() {
return new SymbolClass();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((SymbolClass)element).Name;
}
}
[ConfigurationCollection(typeof(Symbol), AddItemName = "Symbol")]
public class SymbolClass : ConfigurationElementCollection {
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public String Name {
get {
return this["name"] as String;
}
}
protected override ConfigurationElement CreateNewElement() {
return new Symbol();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((Symbol)element).Name;
}
}
[ConfigurationCollection(typeof(TemplateValue), AddItemName = "add")]
public class Symbol : ConfigurationElementCollection {
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public String Name {
get {
return this["name"] as String;
}
}
[ConfigurationProperty("template", IsRequired = false)]
public String Template {
get {
return this["template"] as String;
}
}
[ConfigurationProperty("dataname", IsRequired = false)]
public String DataName {
get {
return this["dataname"] as String;
}
}
protected override ConfigurationElement CreateNewElement() {
return new TemplateValue();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((TemplateValue)element).Index;
}
}
public class TemplateValue : ConfigurationElement {
[ConfigurationProperty("index", IsRequired = false, IsKey = true)]
public Int32 Index {
get {
return this["index"] == null ? -1 : Convert.ToInt32(this["index"]);
}
}
[ConfigurationProperty("value", IsRequired = false)]
public String Value {
get {
return this["value"] as String;
}
}
}
When I parse the section with this statement:
symbols = ConfigurationManager.GetSection("EmailSymbols") as EmailSymbols;
I receive this error message: "Unrecognized element 'Symbol'."
This is simply an area of .NET that I don't know my way around. Any help that anyone could give would be most appreciated.
Does my XML definition make sense and is it in the correct form? I want a collection of SymbolClass, each containing a collection of Symbol, each containing a collection of TemplateValue.
Again, thanks for your help.
Best Regards,
Jimmy
You could try to override the Init() method of the SymbolClass class:
protected override void Init()
{
base.Init();
this.AddElementName = "Symbol";
}
You an also remove [ConfigurationCollection(typeof(SymbolClass), AddItemName = "SymbolClass")] and the others like it from above the class declarations as their not doing anything.

De-sererialzing JSON using JSONConvert - doesn't compile

I'm using VS2008. I've referenced the Newtonsoft.Json (Json.Net) library (v. 3.5) (just the dll... didn't see documentation on what to do with the .pdb and xml file). I'm running .Net 3.5 on server 2k3. Other webmethods within the file are successfully using Serialization.Json.
No errors indicated by IntelliSense... but it wont compile. Giving 'The type or namespace' var could not be found. (indicated by the 'v').
using Newtonsoft.Json;
[WebMethod(EnableSession = true)]
public string EvaluationTest(String EvalData)
{ v
var EvalList = JsonConvert.DeserializeObject<EvaluationCollection>(EvalData);
int rowscount = EvalList.Eval.Count;
int firstobject = EvalList.eval.es;
}
my classes:
namespace MyNamespace
{
public abstract class EvaluationCollection
{
public abstract OneEvaluation eval { get; set; }
private List<OneEvaluation> _eval = new List<OneEvaluation>();
public List<OneEvaluation> Eval = new List<OneEvaluation>();
public EvaluationCollection()
{
}
}
public class OneEvaluation
{
private int _EvalSession = 0;
private String _Comment = " ";
private String _DataDate;
public OneEvaluation()
{
}
public int es { // EvalSession
get { return _EvalSession; }
set { _EvalSession = value; }
}
...
}
}
I'm wondering... did I not reference this correctly?
The problem with this approach... was my web.config.
For those interested... I have both vb and c# on the website - and I needed to add the following section
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp"
extension=".cs"
warningLevel="4"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>

Including static html file from ~/Content into ASP.NET MVC view

I've got master page in my project, which contains some information about site copyright and some contact info in it. I'd like to take it out of master page and place it in a static files (for some reason, these files must be placed in ~/Content folder). Is there a way that I can tell in my view something like
<% Html.Include("~/Content/snippet.html") %> // not a real code
?
You are better off using a partial view (even if it only contains static text) and include it with the Html.Partial helper. But if you insist:
<%= File.ReadAllText(Server.MapPath("~/Content/snippet.html")) %>
If you are in .Net MVC 5 and want to include a HTML file a partial file without having Razor that render it:
#Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Shared/ICanHaz.html")))
Use your own view engine
using
#Html.Partial("_CommonHtmlHead")
as
/Views/Shared/_CommonHtmlHead.html
or
/Views/MyArea/Shared/_CommonHtmlHead.htm
is the best for me.
Creating your own view engine for this by using the System.Web.Mvc.VirtualPathProviderViewEngine ascending class seems to be relatively easy:
/// <summary>
/// Simple render engine to load static HTML files, supposing that view files has the html/htm extension, supporting replacing tilda paths (~/MyRelativePath) in the content
/// </summary>
public class HtmlStaticViewEngine : VirtualPathProviderViewEngine
{
private static readonly ILog _log = LogManager.GetLogger(typeof (HtmlStaticViewEngine));
protected readonly DateTime? AbsoluteTimeout;
protected readonly TimeSpan? SlidingTimeout;
protected readonly CacheItemPriority? Priority;
private readonly bool _useCache;
public HtmlStaticViewEngine(TimeSpan? slidingTimeout = null, DateTime? absoluteTimeout = null, CacheItemPriority? priority = null)
{
_useCache = absoluteTimeout.HasValue || slidingTimeout.HasValue || priority.HasValue;
SlidingTimeout = slidingTimeout;
AbsoluteTimeout = absoluteTimeout;
Priority = priority;
AreaViewLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.html",
"~/Areas/{2}/Views/{1}/{0}.htm",
"~/Areas/{2}/Views/Shared/{0}.html",
"~/Areas/{2}/Views/Shared/{0}.htm"
};
AreaMasterLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.html",
"~/Areas/{2}/Views/{1}/{0}.htm",
"~/Areas/{2}/Views/Shared/{0}.html",
"~/Areas/{2}/Views/Shared/{0}.htm"
};
AreaPartialViewLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}.html",
"~/Areas/{2}/Views/{1}/{0}.htm",
"~/Areas/{2}/Views/Shared/{0}.html",
"~/Areas/{2}/Views/Shared/{0}.htm"
};
ViewLocationFormats = new[]
{
"~/Views/{1}/{0}.html",
"~/Views/{1}/{0}.htm",
"~/Views/Shared/{0}.html",
"~/Views/Shared/{0}.htm"
};
MasterLocationFormats = new[]
{
"~/Views/{1}/{0}.html",
"~/Views/{1}/{0}.htm",
"~/Views/Shared/{0}.html",
"~/Views/Shared/{0}.htm"
};
PartialViewLocationFormats = new[]
{
"~/Views/{1}/{0}.html",
"~/Views/{1}/{0}.htm",
"~/Views/Shared/{0}.html",
"~/Views/Shared/{0}.htm"
};
FileExtensions = new[]
{
"html",
"htm",
};
}
protected virtual string GetContent(string viewFilePath)
{
string result = null;
if (!string.IsNullOrWhiteSpace(viewFilePath))
{
if (_useCache)
{
result = TryCache(viewFilePath);
}
if (result == null)
{
using (StreamReader streamReader = File.OpenText(viewFilePath))
{
result = streamReader.ReadToEnd();
}
result = ParseContent(result);
if (_useCache)
{
CacheIt(viewFilePath, result);
}
}
}
return result;
}
static readonly Regex TildaRegularExpression = new Regex(#"~/", RegexOptions.Compiled);
/// <summary>
/// Finds all tilda paths in the content and replace it for current path
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
protected virtual string ParseContent(string content)
{
if (String.IsNullOrWhiteSpace(content))
{
return content;
}
string absolutePath = VirtualPathUtility.ToAbsolute("~/");
string result = TildaRegularExpression.Replace(content, absolutePath);
return result;
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
HttpContextBase httpContextBase = controllerContext.RequestContext.HttpContext;
string filePath = httpContextBase.Server.MapPath(partialPath);
string content = GetContent(filePath);
return new StaticView(content);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
HttpContextBase httpContextBase = controllerContext.RequestContext.HttpContext;
string result = null;
if (!string.IsNullOrWhiteSpace(masterPath))
{
string filePath = httpContextBase.Server.MapPath(masterPath);
result = GetContent(filePath);
}
string physicalViewPath = httpContextBase.Server.MapPath(viewPath);
result += GetContent(physicalViewPath);
return new StaticView(result);
}
protected virtual string TryCache(string filePath)
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null && httpContext.Cache != null)
{
string cacheKey = CacheKey(filePath);
return (string)httpContext.Cache[cacheKey];
}
return null;
}
protected virtual bool CacheIt(string filePath, string content)
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null && httpContext.Cache != null)
{
string cacheKey = CacheKey(filePath);
httpContext.Cache.Add(cacheKey, content, new CacheDependency(filePath), AbsoluteTimeout.GetValueOrDefault(Cache.NoAbsoluteExpiration), SlidingTimeout.GetValueOrDefault(Cache.NoSlidingExpiration), Priority.GetValueOrDefault(CacheItemPriority.AboveNormal), CacheItemRemovedCallback);
return true;
}
return false;
}
protected virtual string CacheKey(string serverPath)
{
return serverPath;
}
protected virtual void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
_log.InfoFormat("CacheItemRemovedCallback(string key='{0}', object value = ..., {1} reason={2})", key, reason.GetType().Name, reason);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Add(new HtmlStaticViewEngine(new TimeSpan(12,0,0,0)));
}
}
public class StaticView : IView
{
private readonly string _text;
public StaticView(string text)
{
_text = text;
}
public void Render(ViewContext viewContext, TextWriter writer)
{
if (! string.IsNullOrEmpty(_text))
{
writer.Write(_text);
}
}
}
NOTE:
This code is tested only with simple usage for rendering
partial views
Is there a reason you are holding the content in an HTML file rather than a partial view?
If you create a file called snippet.ascx in your Views/Shared folder you can import the content of that snippet.ascx file into any view by using <% Html.RenderPartial("snippet"); %>
To include static html file into a MVC View goes like this:
<!-- #include virtual="~\Content\snippet.htm" -->
For ASP .NET Core 3.1 Razor page you can do it like this:
#Html.Raw(System.IO.File.ReadAllText("wwwroot/Content/snippet.html"));
See documentation regarding static files here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1