Программно изменение встроенного ресурса перед регистрацией / ссылкой на него на странице
-
24-09-2019 - |
Вопрос
Во-первых, «модификация» может быть неправильным сроком, я вижу, что несколько человек опубликовали онлайн, просто спрашивая, могут ли они модифицировать встроенный ресурс. То, что я хочу, это использовать ресурс в мою сборке как своего рода шаблон, который я бы сделал находку и заменить на перед регистрацией его на странице - это возможно?
Например; Скажем, у меня есть несколько строк jQuery в качестве встроенного ресурса в моем сборке, и в этом скрипте я ссылаюсь на имя класса CSS, которое может быть установлено Pront-end Programmer. Поскольку я не знаю, что класс CSS будет до реализации, есть ли способ проходить через встроенный ресурс и замена, скажем, $ MyClass $ с ISTCLASSNAME.
Любая помощь будет оценена, если это невозможно, то, по крайней мере, скажу мне, чтобы я мог перестать преследовать мой хвост.
Решение
Я решил мою маленькую проблему, создав HTTP-обработчик. В этом случае он называется DynamicClientScript.axd.
Я сделал несколько сокращений из моего кода, чтобы дать вам представление. Ниже приведен код стандартного URL-адреса встроенного ресурса и принимает строку запроса, чтобы добавить к пути к моему обработчику.
/// <summary>
/// Gets the dynamic web resource URL to reference on the page.
/// </summary>
/// <param name="type">The type of the resource.</param>
/// <param name="resourceName">Name of the resource.</param>
/// <returns>Path to the web resource.</returns>
public string GetScriptResourceUrl(Type type, string resourceName)
{
this.scriptResourceUrl = this.currentPage.ClientScript.GetWebResourceUrl(type, resourceName);
string resourceQueryString = this.scriptResourceUrl.Substring(this.scriptResourceUrl.IndexOf("d="));
DynamicScriptSessionManager sessMngr = new DynamicScriptSessionManager();
Guid paramGuid = sessMngr.StoreScriptParameters(this.Parameters);
return string.Format("/DynamicScriptResource.axd?{0}¶mGuid={1}", resourceQueryString, paramGuid.ToString());
}
/// <summary>
/// Registers the client script include.
/// </summary>
/// <param name="key">The key of the client script include to register.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="resourceName">Name of the resource.</param>
public void RegisterClientScriptInclude(string key, Type type, string resourceName)
{
this.currentPage.ClientScript.RegisterClientScriptInclude(key, this.GetScriptResourceUrl(type, resourceName));
}
Затем обработчик принимает строку запроса для создания URL на стандартный ресурс. Читает ресурс и заменяет каждую клавишу его значение в коллекции словаря (DynamicClientScriptParameters).
PARAMGUID - это идентификатор, используемый для получения правильного коллекции параметров сценария.
Что делает обработчик ...
public void ProcessRequest(HttpContext context)
{
string d = HttpContext.Current.Request.QueryString["d"];
string t = HttpContext.Current.Request.QueryString["t"];
string paramGuid = HttpContext.Current.Request.QueryString["paramGuid"];
string urlFormatter = "http://" + HttpContext.Current.Request.Url.Host + "/WebResource.axd?d={0}&t={1)";
// URL to resource.
string url = string.Format(urlFormatter, d, t);
string strResult = string.Empty;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
strResult = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
DynamicScriptSessionManager sessionManager = (DynamicScriptSessionManager)HttpContext.Current.Application["DynamicScriptSessionManager"];
DynamicClientScriptParameters parameters = null;
foreach (var item in sessionManager)
{
Guid guid = new Guid(paramGuid);
if (item.SessionID == guid)
{
parameters = item.DynamicScriptParameters;
}
}
foreach (var item in parameters)
{
strResult = strResult.Replace("$" + item.Key + "$", item.Value);
}
// Display results to a webpage
context.Response.Write(strResult);
}
Тогда в моем коде, где я хочу ссылаться на мой ресурс, я использую следующее.
DynamicClientScript dcs = new DynamicClientScript(this.GetType(), "MyNamespace.MyScriptResource.js");
dcs.Parameters.Add("myParam", "myValue");
dcs.RegisterClientScriptInclude("scriptKey");
Тогда скажите, что мой сценарий ресурс содержит:
alert('$myParam$');
Он выводится, как если бы это было:
alert('myValue');
Мой код также делает какое-то кеширование (используя DynamicsCriptsessionManager), но вы получаете идею ...
Ваше здоровье
Другие советы
В вашем CodeBehinding вы можете прочитать содержимое встроенного ресурса, выключить все, что вы хотите, а затем напишите новое содержимое в ответ. Что-то вроде этого:
protected void Page_Load(object sender, EventArgs e)
{
string contents = ReadEmbeddedResource("ClassLibrary1", "ClassLibrary1.TestJavaScript.js");
//replace part of contents
//write new contents to response
Response.Write(String.Format("<script>{0}</script>", contents));
}
private string ReadEmbeddedResource(string assemblyName, string resouceName)
{
var assembly = Assembly.Load(assemblyName);
using (var stream = assembly.GetManifestResourceStream(resouceName))
using(var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}