asp.Net   发布时间:2022-04-05  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了asp.net-web-api – 不能构造String类型大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Web.api和Unity,当我尝试打开默认的“帮助”区域时,我收到以下错误:
[InvalidoperationException: The type String cAnnot be constructed. You must configure the      container to supply this value.]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsnonPrimitive(IBuilderContext context,SELEctedConstructor SELEctedConstructor) +280
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context) +356
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context,NamedTypeBuildKey buildKey) +205
   Microsoft.Practices.ObjectBuilder2.buildPlanStrategy.PreBuildUp(IBuilderContext context) +231
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
   Microsoft.Practices.ObjectBuilder2.builderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
   Microsoft.PracticeS.Unity.objectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
   BuildUp_System.Web.http.httpRouteCollection(IBuilderContext ) +202
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.buildUp(IBuilderContext context) +42
   Microsoft.Practices.ObjectBuilder2.buildPlanStrategy.PreBuildUp(IBuilderContext context) +319
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
   Microsoft.Practices.ObjectBuilder2.builderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
   Microsoft.PracticeS.Unity.objectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
   BuildUp_System.Web.http.httpConfiguration(IBuilderContext ) +202
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.buildUp(IBuilderContext context) +42
   Microsoft.Practices.ObjectBuilder2.buildPlanStrategy.PreBuildUp(IBuilderContext context) +319
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
   Microsoft.Practices.ObjectBuilder2.builderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
   Microsoft.PracticeS.Unity.objectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
   BuildUp_API.Areas.HelpPage.Controllers.HelpController(IBuilderContext ) +204
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.buildUp(IBuilderContext context) +42
   Microsoft.Practices.ObjectBuilder2.buildPlanStrategy.PreBuildUp(IBuilderContext context) +319
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
   Microsoft.PracticeS.Unity.UnityContainer.DoBuildUp(Type t,Object exisTing,String name,IEnumerable`1 resolverOverrides) +373


[ResolutionFailedException: Resolution of the dependency failed,type = "API.Areas.HelpPage.Controllers.HelpController",name = "(nonE)".
Exception occurred while: while resolving.
Exception is: InvalidoperationException - The type String cAnnot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception,the container was:

   Resolving API.Areas.HelpPage.Controllers.HelpController,(nonE)
  Resolving parameter "config" of constructor API.Areas.HelpPage.Controllers.HelpController(System.Web.http.httpConfiguration config)
Resolving System.Web.http.httpConfiguration,(nonE)
Resolving parameter "routes" of constructor System.Web.http.httpConfiguration(System.Web.http.httpRouteCollection routes)
  Resolving System.Web.http.httpRouteCollection,(nonE)
  Resolving parameter "virtualPathRoot" of constructor System.Web.http.httpRouteCollection(System.String virtualPathRoot)
    Resolving System.String,(nonE)
]
   Microsoft.PracticeS.Unity.UnityContainer.DoBuildUp(Type t,IEnumerable`1 resolverOverrides) +436
   Microsoft.PracticeS.Unity.UnityContainer.DoBuildUp(Type t,IEnumerable`1  resolverOverrides) +50
   Microsoft.PracticeS.Unity.UnityContainer.Resolve(Type t,ResolverOverride[] resolverOverrides) +48
   Microsoft.PracticeS.Unity.UnityContainerExtensions.Resolve(IUnityContainer container,Type t,ResolverOverride[] overrides) +61
   Unity.Mvc4.UnityDependencyResolver.Getservice(Type serviCETypE) +140
   System.Web.Mvc.DefaultControllerActivator.Create(requestContext requestContext,Type controllerTypE) +87

[InvalidoperationException: An error occurred when trying to create a controller of type     'API.Areas.HelpPage.Controllers.HelpController'. Make sure that the controller has a parameterless    public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(requestContext requestContext,Type controllerTypE) +247
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(requestContext requestContext,Type controllerTypE) +438
   System.Web.Mvc.DefaultControllerFactory.CreateController(requestContext requestContext,String controllerName) +226
   System.Web.Mvc.MvcHandler.ProcessrequesTinit(httpContextBase httpContext,IController& controller,IControllerFactory& factory) +326
   System.Web.Mvc.MvcHandler.beginProcessrequest(httpContextBase httpContext,AsyncCallBACk callBACk,Object statE) +177
   System.Web.Mvc.MvcHandler.beginProcessrequest(httpContext httpContext,Object statE) +88
    System.Web.Mvc.MvcHandler.System.Web.IhttpAsyncHandler.beginProcessrequest(httpContext context,AsyncCallBACk cb,Object extraData) +50
   System.Web.CallHandlerEXECUTIONStep.System.Web.httpApplication.IEXECUTIONStep.Execute() +301
   System.Web.httpApplication.ExecuteStep(IEXECUTIONStep step,Boolean& completedSynchronously) +155

我是新来的团结,我确定我错过了一步。
在webapiconfig.cs中:

public static void Register(httpConfiguration config)
{
    config.Routes.MaphttpRoute(
    name: "DefaultApi",routeTemplate: "api/{Controller}/{action}/{iD}",defaults: new { id = RouteParameter.optional }
    );

    //Custom formatter
    config.Formatters.Clear();
    config.Formatters.Add(new JSONPFormater());

    config.EnableSystemDiagnosticsTracing();

    //Setup DI
    Bootstrapper.Initialise();
}

Bootstraper.cs(默认值)

public static class Bootstrapper
  {
    public static IUnityContainer Initialise()
    {
      var container = BuildUnityContainer();

      DependencyResolver.SetResolver(new UnityDependencyResolver(container));

      return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

      // register all your components with the container here
      // it is NOT necessary to register your controllers

      // e.g. container.RegisterType<ITestservice,Testservice>();    
      RegisterTypes(container);

      return container;
    }

    public static void RegisterTypes(IUnityContainer container)
    {

    }
  }

我尝试在一个web.config
web.config中

<configSections>
    <!-- For more information on Entity Framework configuration,visit        http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework"     type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,EntityFramework,Version=5.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="unity"  type="Microsoft.PracticeS.Unity.Configuration.UnityConfigurationSection,Microsoft.PracticeS.Unity.Configuration"/>
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data source=(LocalDb)\v11.0;Initial Catalog=aspnet-API-20130708152001;Integrated     Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-API-20130708152001.mdf" />
    <add name="<REMOVED>DBEntities" connectionString="metadata=res://*/Models.DAl.<REMOVED>.csdl|res://*/Models.DAl.<REMOVED>.ssdl|res://*/Models.DAl.<REMOVED>.msl;provider=System.Data.SqlClient;provider connection String=&quot;data source=<REMOVED>;initial catalog=<REMOVED>;persist security info=True;user id=<REMOVED>;password=<REMOVED>;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<!--unity setTing-->
<unity>
    <containers>
        <types>
            <register type="API.Areas.HelpPage.Controllers.HelpController,API">
                <constructor>
                    <param valu=""></param>
            </constructor>
            </register>
        </types>
    </containers>
</unity>

我朝着正确的方向前进吗?

谢谢

更新:
Helpcontroller.cs:

public class HelpController : Controller
    {
        public HelpController()
            : this(GlobalConfiguration.Configuration)
        {
        }

        public HelpController(httpConfiguration config)
        {
            Configuration = config;
        }

        public httpConfiguration Configuration { get; private set; }

        public ActionResult Index()
        {
            return View(Configuration.services.GetApiExplorer().ApiDescriptions);
        }

        public ActionResult Api(String apiId)
        {
            if (!String.IsNullOrEmpty(apiId))
            {
                HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
                if (apiModel != null)
                {
                    return View(apiModel);
                }
            }

            return View("Error");
        }
    }

url我正在尝试访问:http:// hostname:port / Help

解决方法

作为你的代码示例,我假设你是一个控制器,而不是一个API控制器(从web api)。

您的api控制器依赖于httpConfiguration的构造函数。容器可能没有这种类型的定义,因此不知道如何解决它,并且错误消息上的字符串应该来自这种类型作为依赖。我建议您使用GlobalConfiguration静态类并访问Configuration属性以获取httpConfiguration实例。您可以在属性中抽象出样本:

// include this namespace
using System.Web.http;

public class HelpController : Controller
{
    // remove the constructors...

    // property
    protected static httpConfiguration Configuration
    {
        get { return GlobalConfiguration.Configuration; }
    }

    public ActionResult Index()
    {
        return View(this.Configuration.services.GetApiExplorer().ApiDescriptions);
    }

    public ActionResult Api(String apiId)
    {
        if (!String.IsNullOrEmpty(apiId))
        {
            HelpPageApiModel apiModel = this.Configuration.GetHelpPageApiModel(apiId);
            if (apiModel != null)
            {
                return View(apiModel);
            }
        }

        return View("Error");
    }
}

现在,如果您使用的是Api控制器,则只需直接访问ApiController(Api控制器的基类)上的this.Configuration属性,并获取一个httpConfiguration实例。

大佬总结

以上是大佬教程为你收集整理的asp.net-web-api – 不能构造String类型全部内容,希望文章能够帮你解决asp.net-web-api – 不能构造String类型所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。