MVC .NETコアWebアプリケーションに最新のVS.2017アップデートとテンプレートを使用しています。私は、外部のアセンブリでViewComponentsを使いたいと決めたのは、奇妙なトリックなしには不可能であることを示すいくつかの投稿を読んでからです。外部アセンブリ内のViewComponentが見つかりません
私は私のメインWebアプリケーションを持っていて、次に「外部アセンブリ」であるという名前の.NET Frameworkクラスライブラリを作成しました。その中にViewFeatures NuGetをインストールしました。 /Views/Shared/Components/GoogleAdsense/Default.cshtmlにViewコンポーネントCSHTMLを作成しました。
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
<EmbeddedResource Include="Views\Shared\Components\GoogleAdsense\Default.cshtml" />
</ItemGroup>
ビューコンポーネントは、実際には非常に簡単です::メインプロジェクトに続いて
namespace MySite.Components.ViewComponents {
[ViewComponent(Name = "GoogleAdsense")]
public class GoogleAdsense : ViewComponent {
public async Task<IViewComponentResult> InvokeAsync(string adSlot, string clientId, string adStyle = "")
{
var model = await GetConfigAsync(adSlot, clientId, adStyle);
return View(model);
}
private Task<GoogleAdUnitCompModel> GetConfigAsync(string adSlot, string clientId, string adStyle)
{
GoogleAdUnitCompModel model = new GoogleAdUnitCompModel
{
ClientId = clientId, // apparently we can't access App_Data because there is no AppDomain in .NET core
SlotNr = adSlot,
Style = adStyle
};
return Task.FromResult(model);
}
}
}
(ASP
は、私は私のCSPROJが既に埋め込まれたリソースとしてGoogleAdSenseを持っていることに気づきました。 NET Core Webアプリケーション) File Provider NuGetをインストールし、スタートアップを変更しました。services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(new EmbeddedFileProvider(
typeof(MySite.Components.ViewComponents.GoogleAdsense).GetTypeInfo().Assembly,
"MySite.Components.ViewComponents"
));
});
ジェネリックを使用する) @using MySite.Components.ViewComponents
:
@Component.InvokeAsync(nameof(GoogleAdsense), new { adSlot = "2700000000", clientId = "ca-pub-0000000000000000", adStyle="" })
そして私は
*InvalidOperationException: A view component named 'GoogleAdsense' could not be found.*
はまたがNameOf(なしの表記法を使用してみましたというエラーが出ます: は、その後、私は、このようなビューにビューコンポーネントを使用しようInvokeAsyncのためのパラメータが、それはあまりにも失敗しても
*"Argument 1: cannot convert from 'method group' to 'object'"*
そしてTagHelperフォームを使用して、単純に認識されていないHTMLとしてレンダリング:
<vc:GoogleAdsense adSlot = "2700000000" clientId = "ca-pub-0000000000000000"></vc:GoogleAdsense>
最後に、本体(実際のWebアプリケーション)上で、私はそれが埋め込まれたことを確認するために、外部組立式のGetManifestResourceNamesを()を使用し、返されたリストは、それがリストされていたとして:
[0] = "MySite.Components.Views.Shared.Components.GoogleAdsense.Default.cshtml"
NuGetパッケージの生成とインストールの手順については、この回答が役立つでしょうか? – Gary99
私は何とかそれを両方の方法で動かすことができました。しかし、ViewComponentが配置されている外部アセンブリがASP.NET Coreプロジェクトであることを確認するだけです。プロジェクトのプロパティをクリックして、[パッケージ]タブで、最初のビルドNuGetパッケージオプションをチェックします。ビルドが成功すると、.nupkgはbin \ Releaseまたはbin \ Debugフォルダーにあります。自分のリポジトリにコピーし、そこからインストールします。構築したNuGetパッケージを自分のNuGet(ローカル)リポジトリに自動的に展開するビルドタスクを追加しました。 –
これはNuGetパッケージのやり方です。 dll参照として動作させることができれば、何をしましたか?私がdllとしてパッケージに含めたとき、私はviewコンポーネントがエラーを見つけることができなくなってきていました。 –