gpt4 book ai didi

asp.net-core - 如何在 Asp.net 核心服务类中调用 View 组件?

转载 作者:行者123 更新时间:2023-12-03 19:01:08 26 4
gpt4 key购买 nike

我需要在服务类(不是 Controller )中调用 View 组件。我的目标是将 View 组件呈现为字符串,然后处理 HtmlString .

我可以在 ActionContext 的 Controller 中找到渲染 View 组件的帮助。可用,但我无法从 Controller 调用我的服务。请问有什么帮助吗?我很高兴使用 Mock 和默认依赖注入(inject)。

目前,我正在使用 mvc 6 beta 2。这是我类(class)的代码

public class MyClass
{
Microsoft.AspNet.Mvc.DefaultViewComponentHelper viewComponentHelper = null;
Microsoft.AspNet.Mvc.Razor.RazorView razorView = null;

public MyClass(IViewComponentSelector selector, IViewComponentInvokerFactory factory,
IRazorPageFactory razorPageFactory, IRazorViewEngine razorViewEngine, IRazorPageActivator pageActivator,
IViewStartProvider viewStartProvider)
{
viewComponentHelper = new DefaultViewComponentHelper(selector, factory);
razorView = new RazorView(razorViewEngine, pageActivator, viewStartProvider, null, true);
}

public void MyAction
{

var view = new Mock<IView>().Object;

var actionContext = new ActionContext(new RouteContext(new DefaultHttpContext()), new ActionDescriptor());
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
var viewContext = new ViewContext(actionContext, view, viewData, TextWriter.Null);

viewComponentHelper.Contextualize(viewContext);
var result = viewComponentHelper.Invoke("MyView").ToString();
}
}

我收到以下异常
   at Microsoft.Framework.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.AspNet.Mvc.DefaultViewComponentActivator.<>c__DisplayClass6.<CreateActivateInfo>b__7(ViewContext viewContext)
at Microsoft.AspNet.Mvc.PropertyActivator`1.Activate(Object view, TContext context)
at Microsoft.AspNet.Mvc.DefaultViewComponentActivator.Activate(Object viewComponent, ViewContext context)
at Microsoft.AspNet.Mvc.DefaultViewComponentInvoker.CreateComponent(ViewContext context)
at Microsoft.AspNet.Mvc.DefaultViewComponentInvoker.InvokeSyncCore(MethodInfo method, ViewContext context)
at Microsoft.AspNet.Mvc.DefaultViewComponentInvoker.Invoke(ViewComponentContext context)
at Microsoft.AspNet.Mvc.DefaultViewComponentHelper.InvokeCore(TextWriter writer, Type componentType, Object[] arguments)
at Microsoft.AspNet.Mvc.DefaultViewComponentHelper.Invoke(Type componentType, Object[] args)
at Microsoft.AspNet.Mvc.DefaultViewComponentHelper.Invoke(String name, Object[] args)

最佳答案

在启动文件的 ConfigureServices 部分中,您需要注册您的服务,即:

   public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container.
//services.AddMvc();

services.AddTransient...
}

关于asp.net-core - 如何在 Asp.net 核心服务类中调用 View 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28346501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com