Мой проект ASP не может получить доступ к классам из созданного мной пакета NuGet.C#

Место общения программистов C#
Ответить
Anonymous
 Мой проект ASP не может получить доступ к классам из созданного мной пакета NuGet.

Сообщение 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);
}
}
}
Советы по проверке кода и улучшению приветствуются и благодарим вас.


Подробнее здесь: https://stackoverflow.com/questions/793 ... -i-created
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»