Итак, я экспериментирую с созданием пакетов NuGet, и у этого есть вспомогательный тег и метод расширения для IApplicationBuilder, я упаковал пакет и поместил его в локальную папку, добавил папку в источники пакетов. затем установил пакет.
Структура проекта пакета:
TagHelperNuGet/
├── wwwroot/
│ ├── css/
│ │ └── style.cs
│ └── js/
│ └── script.js
├── TagHelpers/
│ └── BtnTagHelper.cs
└── Extensions/
└── StaticFileExtension.cs
Помощник тега распознается (после добавления @addTagHelper *, RazorClassLibraryTest конечно), но метод расширения — нет.
Когда Я пытаюсь импортировать пространство имен в файл Program.cs
using RazorClassLibraryTest.Extensions;
Я понимаю
The type or namespace name 'Extensions' does not exist in the namespace 'RazorClassLibraryTest' (are you missing an assembly reference?)
Но когда я делаю то же самое для пространства имен вспомогательного тега, оно импортируется без каких-либо проблем.
using RazorClassLibraryTest.TagHelpers;
Это код обоих файлов:
AlertBtnTagHleper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace RazorClassLibraryTest.TagHelpers
{
[HtmlTargetElement("alert-btn")]
public class AlertBtnTagHelper : TagHelper
{
[HtmlAttributeName("text")]
public string Text { get; set; } = "Show Alert";
[HtmlAttributeName("message")]
public string Message { get; set; } = "Hello World!";
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "button";
output.Attributes.SetAttribute("type", "button");
output.Attributes.SetAttribute("class", "btn-alert");
output.Attributes.SetAttribute("onclick", $"showAlert('{Message}')");
output.Content.SetContent(Text);
}
}
}
StaticFilesExtention.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using System.Reflection;
namespace RazorClassLibraryTest.Extensions
{
public static class StaticFilesExtension
{
///
/// Configures the application to serve static files from a specified staticFilesRoot path.
///
/// The application builder.
/// The staticFilesRoot path to serve static files from. Defaults to _content/RazorClassLibraryTest/.
/// The application builder.
public static IApplicationBuilder UseTagStatics(this IApplicationBuilder app, string? staticFilesRoot)
{
if (string.IsNullOrWhiteSpace(staticFilesRoot))
return app;
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments(staticFilesRoot))
{
Assembly assembly = Assembly.GetAssembly(typeof(StaticFilesExtension))!;
string? assemblyName = assembly.GetName().Name;
if (string.IsNullOrWhiteSpace(assemblyName))
throw new InvalidOperationException("The assembly name could not be determined.");
string assetPath = context.Request.Path.Value[(staticFilesRoot.Length + 1)..];
context.Request.Path = $"/_content/{assemblyName}/{assetPath}";
}
await next();
});
return app;
}
///
/// Configures the application to serve static files from a path specified in the configuration.
///
/// The application builder.
/// The configuration to get the staticFilesRoot path from. Expects the value to be stored in "RazorTag.StaticFilesRoot".
/// The application builder.
public static IApplicationBuilder UseTagStatics(this IApplicationBuilder app, IConfiguration configuration)
{
string? configStaticFilesRoot = configuration["RazorTag:StaticFilesRoot"];
if (string.IsNullOrWhiteSpace(configStaticFilesRoot))
return app;
return app.UseTagStatics(configStaticFilesRoot);
}
}
}
Проверка кода и советы по улучшению приветствуются и спасибо.
Изменить:
Расширения упакованы, но они по-прежнему не работают
Изображение структуры пакета с использованием приложения DotPeek
Редактировать 2:
Код из .csproj< /code>
net8.0
enable
enable
True
Подробнее здесь: https://stackoverflow.com/questions/793 ... -i-created
Мой проект ASP не может получить доступ к классам из созданного мной пакета NuGet. ⇐ C#
Место общения программистов C#
1737385958
Anonymous
Итак, я экспериментирую с созданием пакетов NuGet, и у этого есть вспомогательный тег и метод расширения для IApplicationBuilder, я упаковал пакет и поместил его в локальную папку, добавил папку в источники пакетов. затем установил пакет.
Структура проекта пакета:
TagHelperNuGet/
├── wwwroot/
│ ├── css/
│ │ └── style.cs
│ └── js/
│ └── script.js
├── TagHelpers/
│ └── BtnTagHelper.cs
└── Extensions/
└── StaticFileExtension.cs
Помощник тега распознается (после добавления @addTagHelper *, RazorClassLibraryTest конечно), но метод расширения — нет.
Когда Я пытаюсь импортировать пространство имен в файл Program.cs
using RazorClassLibraryTest.Extensions;
Я понимаю
The type or namespace name 'Extensions' does not exist in the namespace 'RazorClassLibraryTest' (are you missing an assembly reference?)
Но когда я делаю то же самое для пространства имен вспомогательного тега, оно импортируется без каких-либо проблем.
using RazorClassLibraryTest.TagHelpers;
Это код обоих файлов:
AlertBtnTagHleper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace RazorClassLibraryTest.TagHelpers
{
[HtmlTargetElement("alert-btn")]
public class AlertBtnTagHelper : TagHelper
{
[HtmlAttributeName("text")]
public string Text { get; set; } = "Show Alert";
[HtmlAttributeName("message")]
public string Message { get; set; } = "Hello World!";
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "button";
output.Attributes.SetAttribute("type", "button");
output.Attributes.SetAttribute("class", "btn-alert");
output.Attributes.SetAttribute("onclick", $"showAlert('{Message}')");
output.Content.SetContent(Text);
}
}
}
StaticFilesExtention.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using System.Reflection;
namespace RazorClassLibraryTest.Extensions
{
public static class StaticFilesExtension
{
///
/// Configures the application to serve static files from a specified staticFilesRoot path.
///
/// The application builder.
/// The staticFilesRoot path to serve static files from. Defaults to _content/RazorClassLibraryTest/.
/// The application builder.
public static IApplicationBuilder UseTagStatics(this IApplicationBuilder app, string? staticFilesRoot)
{
if (string.IsNullOrWhiteSpace(staticFilesRoot))
return app;
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments(staticFilesRoot))
{
Assembly assembly = Assembly.GetAssembly(typeof(StaticFilesExtension))!;
string? assemblyName = assembly.GetName().Name;
if (string.IsNullOrWhiteSpace(assemblyName))
throw new InvalidOperationException("The assembly name could not be determined.");
string assetPath = context.Request.Path.Value[(staticFilesRoot.Length + 1)..];
context.Request.Path = $"/_content/{assemblyName}/{assetPath}";
}
await next();
});
return app;
}
///
/// Configures the application to serve static files from a path specified in the configuration.
///
/// The application builder.
/// The configuration to get the staticFilesRoot path from. Expects the value to be stored in "RazorTag.StaticFilesRoot".
/// The application builder.
public static IApplicationBuilder UseTagStatics(this IApplicationBuilder app, IConfiguration configuration)
{
string? configStaticFilesRoot = configuration["RazorTag:StaticFilesRoot"];
if (string.IsNullOrWhiteSpace(configStaticFilesRoot))
return app;
return app.UseTagStatics(configStaticFilesRoot);
}
}
}
Проверка кода и советы по улучшению приветствуются и спасибо.
Изменить:
Расширения упакованы, но они по-прежнему не работают
Изображение структуры пакета с использованием приложения DotPeek
Редактировать 2:
Код из .csproj< /code>
net8.0
enable
enable
True
Подробнее здесь: [url]https://stackoverflow.com/questions/79360887/my-asp-project-cant-access-classes-from-a-nuget-package-i-created[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия