应用程序抛出了未处理的异常。 System.InvalidOperationException:无法>解析

时间:2017-04-04 19:01:51

标签: c# .net asp.net-web-api asp.net-core asp.net-core-mvc

我有一个简单的asp.net核心web api,我试图只使用visual studio模板默认带来的api /值。但是我收到了这个错误:

  

托管环境:生产内容根路径:C:\ api.E-commerce   现在收听:http://localhost:18401应用程序已启动。按   按Ctrl + C关闭。失败:Microsoft.AspNetCore.Server.Kestrel [13]         连接ID" 0HL3RHG5NLHAL":应用程序抛出了未处理的异常。 System.InvalidOperationException:无法执行   解决类型的服务   ' ECommerce.Api.Repository.Ecommerce.IEcommerceRepository'而   试图激活' ContactsApi.Controllers.ValuesController'。
  在   Microsoft.Extensions.Internal.ActivatorUtilities.GetService(的IServiceProvider   sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)
  在lambda_method(Closure,IServiceProvider,Object [])at   Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance [TInstance](的IServiceProvider   serviceProvider,类型implementationType)at   Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext   上下文)   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(州及放大器;   接下来,范围&amp;范围,对象&amp; state,Boolean&amp; isCompleted)at   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__22.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext   上下文)   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(州及放大器;   接下来,范围&amp;范围,对象&amp; state,Boolean&amp; isCompleted)at   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Authentication.AuthenticationMiddleware 1.<Invoke>d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware 1.d__18.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Authentication.AuthenticationMiddleware 1.<Invoke>d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware 1.d__18.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.d__7.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.d__7.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.d__8.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.d__2.MoveNext()

启动代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Microsoft.EntityFrameworkCore;
using ContactsApi.Contexts;
using ECommerce.Api.Models.ERP;
using ECommerce.Api.Repository.ERP;
using System.IO;
//using Microsoft.AspNetCore.Mvc;
//using Microsoft.AspNetCore.Mvc.Cors.Internal;

namespace ContactsApi
{
    public partial class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

           // var host = new WebHostBuilder()
           //.UseKestrel()
           //.UseContentRoot(Directory.GetCurrentDirectory())
           //.UseIISIntegration() // IMPORTANT!!!
           //.UseStartup<Startup>()
           //.Build();
           // host.Run();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc()
                    .AddJsonOptions(a => a.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); ;

            //using Dependency Injection
            //services.AddSingleton<IContactsRepository, ContactsRepository>();
            //services.AddSingleton<ITodoTerrenoRepository, TodoTerrenoRepository>();

            services.AddDbContext<ContactsContext>(options =>
             options.UseSqlServer(Configuration.GetConnectionString("AuthentConnection")));
            services.AddDbContext<TODOTERRENOContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());
                options.AddPolicy("AllowAllHeaders", builder => builder.AllowAnyHeader());
                options.AddPolicy("AllowCredentials", builder => builder.AllowCredentials());
            });

            services.Configure<IISOptions>(options =>
            {

                options.AutomaticAuthentication = true;
                options.ForwardClientCertificate = true;
                options.ForwardWindowsAuthentication = true;


            });


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseCors("AllowAllOrigins");
            app.UseCors("AllowAllHeader");
            ConfigureAuth(app);
            //app.UseMvc(routes =>
            //{
            //    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            //});           
            //// Shows UseCors with CorsPolicyBuilder.
            //app.UseCors("AllowSpecificOrigin");
            app.UseMvc();
        }
    }
}

更新1

值控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using ECommerce.Api.Repository.Ecommerce;

namespace ContactsApi.Controllers
{
    //[Authorize]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {

        public IEcommerceRepository ContactsRepo { get; set; }


        public ValuesController(IEcommerceRepository _repo)
        {
            ContactsRepo = _repo;
        }
        // GET api/values
       // [HttpGet]
        //public IEnumerable<string> Get()
        //{


        //    ContactsRepo.CrearUsuario();

        //    return new string[] { "value1", "value2" };
        //}

       // [HttpGet]
        [HttpGet("{DatosUsuario}")]
        public string GestionarUsuario(string DatosUsuario)
        {



            return ContactsRepo.GestionarUsuario(DatosUsuario).Result;
        }

        // GET api/values/5
        [HttpGet]
       // public string Get(in)
        public string Get()
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

UDPATE 2

现在我们得到Stackoverflow异常!,日志文件中根本没有任何细节

2 个答案:

答案 0 :(得分:3)

错误消息表明正在点击ValuesController。在尝试实例化此控制器时,IEcommerceRepository在构造函数中使用。 依赖注入框架试图找到类型IEcommerceRepository的实现。

这应该在Startup.cs中注册。您可以注册如下: ConfigureServices方法中的services.AddSingleton<IEcommerceRepository, MyEcommerceRepository>();

答案 1 :(得分:1)

您似乎未将 EcommerceRepository 注册到 IEcommerceRepository

例如,

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddTransient<IEcommerceRepository, EcommerceRepository>();
   ...
}