Web API 2 with attribute routing getting same key error - asp.net-mvc

Why do I keep getting the error below about duplicate keys? This worked fine before I tried attribute routing, but now it does not. If I remove {id:int} it always hits the second method, never the first, even if no ID is supplied.
EventsController
[System.Web.Http.RoutePrefix("api/v1/events")]
public partial class EventsController : System.Web.Http.ApiController
{
[System.Web.Http.Route("")]
public virtual ApiEventsResponse Get([FromUri] ApiEventsRequest request)
{
.....
return response;
}
[System.Web.Http.Route("{id:int}")]
public virtual ApiEventResponse Get(int id, [FromUri] ApiEventRequest request)
{
.....
return response;
}
Error when accessing /api/v1/events?id=12315
Server Error in '/' Application.
An item with the same key has already been added.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: An item with the same key has already been added.
Source Error:
Line 407: AreaRegistration.RegisterAllAreas();
Line 408:
Line 409: GlobalConfiguration.Configure(WebApiConfig.Register);
Line 410: RegisterRoutes(RouteTable.Routes);
Line 411:
Source File: f:\My Webs\BasketballTournaments\MainBranch\Websites\Tournaments\Global.asax.cs Line: 409
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +11187358
System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) +10
System.Web.Http.Routing.InlineRouteTemplateParser.ParseRouteTemplate(String routeTemplate, IDictionary`2 defaults, IDictionary`2 constraints, IInlineConstraintResolver constraintResolver) +363
System.Web.Http.Routing.HttpRouteBuilder.BuildParsingRoute(String routeTemplate, Int32 order, IEnumerable`1 actions) +86
System.Web.Http.HttpConfigurationExtensions.MapHttpAttributeRoutesInternal(HttpConfiguration configuration, HttpRouteBuilder routeBuilder) +232
System.Web.Http.<>c__DisplayClass5.<MapHttpAttributeRoutes>b__4() +13
System.Web.Http.Routing.RouteCollectionRoute.EnsureInitialized(Func`1 initializer) +70
System.Web.Http.<>c__DisplayClass5.<MapHttpAttributeRoutes>b__3(HttpConfiguration config) +63
System.Web.Http.HttpConfiguration.EnsureInitialized() +23
System.Web.Http.GlobalConfiguration.Configure(Action`1 configurationCallback) +57
Tournaments.MvcApplication.OnApplicationStarted() in f:\My Webs\BasketballTournaments\MainBranch\Websites\Tournaments\Global.asax.cs:409
Ninject.Web.Common.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\NinjectHttpApplication.cs:82
[HttpException (0x80004005): An item with the same key has already been added.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9903113
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): An item with the same key has already been added.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9882460
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
WebApiConfig.cs
namespace Tournaments.App_Start
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Filters.Add(new ExceptionHandlingAttribute());
}
}
}

Not an answer but I just went back to my original. I think the original problem is I have two apis, and since you cant namespace web api routes yet there were duplicate key issues because the EventsController was listed twice but under different namespaces. That was the duplicate key issue, but for the {id:int} never working for a query string you got me.
routes.MapHttpRoute(
"DefaultApi",
"api/v{version}/{controller}/{id}",
new { id = RouteParameter.Optional, version = 1 }
);
routes.MapHttpRoute(
"DefaultApiAction",
"api/v{version}/{controller}/{action}"
);

Related

Unity MVC using SOA and gereric Repository and UnitOfWork

I am trying to put together a project that is based on SOA and uses Gereric Repository and UnitOfWork along with Unity.
My problem is that when the controllers try to initialize I get the following error:
The type String cannot be constructed. You must configure the container to supply this value.
I have the following Unity Configuration:
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
public static void RegisterTypes(IUnityContainer container)
{
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IDataContextAsync, MyDbContext>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryProvider, RepositoryProvider>(
new PerRequestLifetimeManager(),
new InjectionConstructor(new object[] { new RepositoryFactories() })
)
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<ApplicationSetting>, Repository<ApplicationSetting>>()
.RegisterType<IApplicationSettingService, ApplicationSettingService>();
container.RegisterType<IRepositoryProvider, RepositoryProvider>(new InjectionConstructor(container));
}
}
The following Activator
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;
using XNETProductQuote.Web;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnityWebActivator), "Shutdown")]
namespace XNETProductQuote.Web
{
/// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
public static class UnityWebActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
My controller that I am trying to load is the following
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XNETProductQuote.Entities ;
using XNETProductQuote.Entities.Models;
using XNETProductQuote.Service;
namespace XNETProductQuote.Controllers
{
public class ApplicationSettingController : Controller
{
private IApplicationSettingService service;
public ApplicationSettingController(IApplicationSettingService svr)
{
service = svr;
}
//
// GET: /ApplicationSetting/
public ActionResult Index()
{
var applicationSettings = service.GetAll();
return View(applicationSettings);
}
}
As far as I can see the Unityconfig Registers the IApplicationSettingService type that should be used to initialise the controller.
am I missing something else?
UPDATE:
The error I get is
[InvalidOperationException: The type String cannot be constructed. You must configure the container to supply this value.]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context) +299
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context) +131
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey) +162
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +245
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +222
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +232
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +222
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +224
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +384
[ResolutionFailedException: Resolution of the dependency failed, type = "XNETProductQuote.Controllers.ApplicationSettingController", 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 XNETProductQuote.Controllers.ApplicationSettingController,(none)
Resolving parameter "svr" of constructor XNETProductQuote.Controllers.ApplicationSettingController(XNETProductQuote.Service.IApplicationSettingService svr)
Resolving XNETProductQuote.Service.ApplicationSettingService,(none) (mapped from XNETProductQuote.Service.IApplicationSettingService, (none))
Resolving parameter "repository" of constructor XNETProductQuote.Service.ApplicationSettingService(Repository.Pattern.Repositories.IRepositoryAsync`1[[XNETProductQuote.Entities.Models.ApplicationSetting, XNETProductQuote.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] repository)
Resolving Repository.Pattern.Ef6.Repository`1[XNETProductQuote.Entities.Models.ApplicationSetting],(none) (mapped from Repository.Pattern.Repositories.IRepositoryAsync`1[XNETProductQuote.Entities.Models.ApplicationSetting], (none))
Resolving parameter "context" of constructor Repository.Pattern.Ef6.Repository`1[[XNETProductQuote.Entities.Models.ApplicationSetting, XNETProductQuote.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]](Repository.Pattern.DataContext.IDataContextAsync context, Repository.Pattern.UnitOfWork.IUnitOfWorkAsync unitOfWork)
Resolving XNETProductQuote.Entities.MyDbContext,(none) (mapped from Repository.Pattern.DataContext.IDataContextAsync, (none))
Resolving parameter "connectionString" of constructor XNETProductQuote.Entities.MyDbContext(System.String connectionString)
Resolving System.String,(none)
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +447
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides) +50
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +48
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +61
Microsoft.Practices.Unity.Mvc.UnityDependencyResolver.GetService(Type serviceType) +142
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +87
[InvalidOperationException: An error occurred when trying to create a controller of type 'XNETProductQuote.Controllers.ApplicationSettingController'. 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) +157
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, 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
My Repository class is as follow
public static class ApplicationSettingRepository
{
public static ApplicationSetting GetByID(this IRepository<ApplicationSetting> repository, int applicationSettingId)
{
return repository.Find(applicationSettingId);
}
public static IEnumerable<ApplicationSetting> GetAll(this IRepository<ApplicationSetting> repository)
{
return repository.Queryable().AsEnumerable();
}
}

The static container already has a kernel associated with it! when deployed to a virtual application

I am trying to get ninject to work in a production environment.
My solution consists of the following projects
Data
Model
WebApi2
MVC5
Everything is getting deployed as webrole to azure.
My api is setup as a virtual application below the mvc site. My application is a multi tenant application so I want users to be able to access the api the same way as the application does e.g.
https://theirbusiness.mydomain.com/api/api-call
For my local development I am using 2 sites not a virtual application as I had to many issues trying to battle with azure to get it working locally. So my service definition has 2 sites created for local work. Locally I have no issues
My website and api both have reference to ninject, my data and model do not.
When I deploy and try to hit the api I get an error
The static container already has a kernel associated with it!
The website doesnt have any issues it just seems to be the api. I added ninject to both using nuget
The stack trace
[NotSupportedException: The static container already has a kernel associated with it!]
Ninject.Web.KernelContainer.set_Kernel(IKernel value) +193
Ninject.Web.NinjectWebHttpApplicationPlugin.Start() +82
Ninject.Web.Common.Bootstrapper.b__0(INinjectHttpApplicationPlugin c) +89
Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable1 series, Action1 action) +283
Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) +410
MyNameSpace.Application.Api.App_Start.NinjectWebCommon.Start() +362
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +417
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
WebActivator.BaseActivationMethodAttribute.InvokeMethod() +761
WebActivator.ActivationManager.RunActivationMethods() +1177
WebActivator.ActivationManager.RunPreStartMethods() +75
WebActivator.ActivationManager.Run() +97
[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +888
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +137
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +160
System.Web.Compilation.BuildManager.ExecutePreAppStart() +142
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +838
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +452
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +99
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +1017
My NinjectWebCommon.cs
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using MyNameSpace.Application.Api.App_Start;
using MyNameSpace.Application.Api.Interface;
using MyNameSpace.Application.Api.Repository;
[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]
namespace MyNameSpace.Application.Api.App_Start
{
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IBusinessRepository>().ToConstant(new BusinessRepository());
kernel.Bind<IEmployeeRepository>().ToConstant(new EmployeeRepository());
}
}
}
My Dependency scope
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.GetAll(serviceType);
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
If I debug locally. Setting the api as my startup project I can run the application without any problems as soon as I deploy it, it fails. I remote logged into the azure webrole and deleted the mvc site keeping just the api site as the root site. This did not help the issue.
Does something look wrong in my above setup?
I believe your problem is the same as mine. The problem is that you have duplicate Ninject.dll or whatever dll from Ninject in your production environment. You have to clean all your existing files before you deploy again. See my solution here:
The static container already has a kernel associated with it
This happened to me, and I just commented on this line: bootstrapper.Initialize(CreateKernel) and the problem it's over.

The controller for path '/Home' was not found or does not implement IController

I've searched the internet high and low and checked all previously answered questions with the same title and I cannot figure this one out.
I return RedirectToAction("Index", "Home") from the action method in my authentication controller and then receive the following exception:
Server Error in '/' Application.
The controller for path '/Home' was not found or does not implement IController.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The controller for path '/Home' was not found or does not implement IController.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): The controller for path '/Home' was not found or does not implement IController.]
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +683921
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +89
Castle.Proxies.Invocations.IControllerFactory_CreateController.InvokeMethodOnTarget() +155
Castle.DynamicProxy.AbstractInvocation.Proceed() +116
Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +85
Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +186
Castle.DynamicProxy.AbstractInvocation.Proceed() +604
Castle.Proxies.IControllerFactoryProxy.CreateController(RequestContext requestContext, String controllerName) +193
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +305
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +87
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +41
[HttpException (0x80004005): Execution of the child request failed. Please examine the InnerException for more information.]
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +785832
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3977
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +275
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +94
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +700
System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +123
Panoptes.Ui.Web.Views.Home.Index.Execute() in c:\Dropbox\Energy Management System\Application\Panoptes\Panoptes.Ui.Web\obj\CodeGen\Views\Home\Index.cshtml:48
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +126
System.Web.WebPages.StartPage.ExecutePageHierarchy() +143
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +181
RazorGenerator.Mvc.PrecompiledMvcView.Render(ViewContext viewContext, TextWriter writer) +952
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +378
Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionResult_callback(ControllerContext controllerContext, ActionResult actionResult) +21
Castle.DynamicProxy.AbstractInvocation.Proceed() +116
Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +85
Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +186
Castle.DynamicProxy.AbstractInvocation.Proceed() +604
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +33
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +854172
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +854172
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +838644
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034
The authentication controller looks as follows:
public class AuthenticationController : Controller
{
private ILogService _logService;
private IEmailProvider _emailProvider;
private IMembershipProvider _membershipProvider;
private IAuthenticationProvider _authenicationProvider;
public AuthenticationController(ILogService logService, IEmailProvider emailProvider, IMembershipProvider membershipProvider, IAuthenticationProvider authenicationProvider)
{
_logService = logService;
_emailProvider = emailProvider;
_membershipProvider = membershipProvider;
_authenicationProvider = authenicationProvider;
}
[AllowAnonymous]
[HttpGet]
////[OutputCache(Duration = 3600, VaryByParam = "none")]
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[HttpPost]
[ValidateHttpAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
if (ModelState.IsValid)
{
if (_membershipProvider.ValidateUser(model.Username, model.Password))
{
_authenicationProvider.AuthenticateUser(model.Username);
////this.HttpContext.User = new GenericPrincipal(new GenericIdentity(model.Username), null);
if (!string.IsNullOrEmpty(returnUrl))
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
_logService.Log(new SecurityException(string.Format("Open redirect to {0} detected (Username {1})", returnUrl, model.Username)));
return View("Index", model);
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError(string.Empty, Resources.Controller.View.Authentication.Index.IncorrectUsernamePassword);
}
}
return View("Index", model);
}
[AllowAnonymous]
[HttpPost]
[ValidateHttpAntiForgeryToken]
public ActionResult ForgotPassword(LoginModel model)
{
if (ModelState.IsValidField("Username"))
{
if (!_membershipProvider.EnablePasswordRetrieval)
{
throw new Exception(Resources.Controller.View.Authentication.Index.PasswordRetreivalNotAllowed);
}
IMembershipUser user = _membershipProvider.FindUsersByName(model.Username).FirstOrDefault();
if (user != null)
{
try
{
_emailProvider.Send(ConfigurationHelper.GetSmtpSettings().Smtp.From, user.EmailAddress, Resources.Global.PasswordRecoveryEmailSubject, user.GeneratePasswordRetreivalEmail());
ModelState.AddModelSuccess(Resources.Controller.View.Authentication.Index.PasswordSentViaEmail);
}
catch (Exception ex)
{
_logService.Log(ex);
ModelState.AddModelError(string.Empty, Resources.Controller.View.Authentication.Index.UnableToRetreivePassword);
}
}
else
{
ModelState.AddModelError(string.Empty, Resources.Controller.View.Authentication.Index.EmailAddressDoesNotExist);
}
}
ViewBag.ShowForgottenPasswordForm = "true";
return View("Index", model);
}
[HttpGet]
public ActionResult Logout()
{
_authenicationProvider.Logout();
ModelState.AddModelInformation(Resources.Controller.View.Authentication.Index.Logout);
return View("Index");
}
}
My HomeController looks as follows:
public class HomeController : Controller
{
private IMembershipProvider _membershipProvider;
private IAuthenticationProvider _authenticationProvider;
public HomeController(IMembershipProvider membershipProvider, IAuthenticationProvider authenticationProvider)
{
_membershipProvider = membershipProvider;
_authenticationProvider = authenticationProvider;
}
public ActionResult Index()
{
return View(_membershipProvider.GetCurrentUser());
}
}
See below my RouteConfig:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Authentication", action = "Index" });
}
}
RouteDebugger returns TRUE for the routes {controller}/{action} and {*catchall} and confirms the AppRelativeCurrentExecutionFilePath as: ~/Home
I have debugged the code and I can successfully debug and step into the HomeController constructor and Index action method. I have also been able to step into the "~/Views/Home/Index.cshtml" however it throws the exception at the line of code:
<span class="username">#Model.UserName</span>
Funnily enough, before I step into this code I can add "#Model.UserName" to my list of watches and I can see the object and its properties fine, but for some reason it throws an exception when stepping into or over this line of code.
If the debugger steps into the HomeController, the Index action method and the Index view, then why is it all of a sudden throwing the exception it can't find the HomeController for the path "~/Home"?
The captured fiddler data can be found at the following link: http://d-h.st/IqV
I have used Razor Generator to compile my views and I am also using Ninject.Mvc to resolve my controllers. It's also worth mentioning I have cleared down and re-generated the compiled views and my project does not contain any registered areas.
Any idea's? this might be simple or an obvious one but I'm new to MVC and am reading/learning as I go.
Thanks
So people can see this question was answered here is why it was throwing the exception and how I fixed it:
The exception was being thrown because of the following line of code in the HomeController Index view:
<i class="icon-key"></i> Log Out
As you can see it's passing the wrong arguments and "Log Out" is being passed in as the action name when infact this should be "Logout". I correct it to the following and it worked:
<i class="icon-key"></i> Log Out
So if you're getting this exception and like me can't understand why then please make sure you check the rest of your code in your view to make sure it is correct. In this instance the framework doesn't provide a meaning exception message and stacktrace.

NullReferenceException in WebConfigScopeDictionary

Occasionally (about once a month) an ASP.NET MVC 3 web application fails with this exception.
System.NullReferenceException: Object reference not set to an instance of an object.
Server stack trace:
at System.Collections.Specialized.NameObjectCollectionBase.BaseGetAllKeys()
at System.Collections.Specialized.NameValueCollection.get_AllKeys()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.<>c__DisplayClass4.<.ctor>b__0()
at System.Lazy`1.CreateValue()
Exception rethrown at [0]:
at System.Lazy`1.get_Value()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value)
at System.Web.Mvc.ViewContext.ScopeGet[TValue](IDictionary`2 scope, String name, TValue defaultValue)
at System.Web.Mvc.ViewContext.ScopeCache..ctor(IDictionary`2 scope)
at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.ViewContext.GetClientValidationEnabled(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.Html.FormExtensions.FormHelper(HtmlHelper htmlHelper, String formAction, FormMethod method, IDictionary`2 htmlAttributes)
at ASP._Page_Views_mywebpage_Create_cshtml.Execute() in c:\App\Views\Mywebpage\Create.cshtml:line 11
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This exception occurs on a line with
#using (Html.BeginForm())
From the moment this exception occurs once, the application is unusable. Every view will start throwing this error. I've looked around in the source code but seem unable to find anything. There are people who experience the same behaviour but with a different error and or by different code.
When digging deeper in the source of WebConfigScopeDictionary you can see that the AppSettings are being read:
public WebConfigScopeDictionary() : this(WebConfigurationManager.AppSettings)
{
}
public WebConfigScopeDictionary(NameValueCollection appSettings)
{
this._items = new Lazy<Dictionary<object, object>>(() => appSettings.AllKeys.ToDictionary((string key) => key, (string key) => appSettings[key], ScopeStorageComparer.Instance));
}
The appsettings come from the ConfigurationManager:
public static NameValueCollection AppSettings
{
get
{
object section = ConfigurationManager.GetSection("appSettings");
if (section == null || !(section is NameValueCollection))
{
throw new ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid"));
}
return (NameValueCollection)section;
}
}
If there would be a problem with the web.config this code should have thrown an exception. But it doesn't. Eventually count is called on the collection that is returned by the AppSettings property. Since it is probably null at this point it throws.
protected string[] BaseGetAllKeys()
{
int count = this._entriesArray.Count;
string[] array = new string[count];
for (int i = 0; i < count; i++)
{
array[i] = this.BaseGetKey(i);
}
return array;
}
If anyone has any ideas, feel free to share.
After enquiring with the ops team it would appear that the application pool was being recycled after the timed interval had expired. This happened during office hours while the application is under a significant load. We've now changed it to recycle at a specific time, which is still a workaround but should prevent the problem from occurring too frequently.

ASP.Net MVC controller route when large records

In my application I have a page that displays a list of records and with every record there is a link to click for more details of that record. It goes to the other controller.
Let me tell a sequence. From 'ToDoListSelect' controller it goes to 'ToDoList' and on clicking the link from ToDoList it goes to 'Info' controller. Everything works fine on my development machine with same database as on the server.
Now, I put the package on server and there it works okay if the records on the page are less than 500 or so. If there are more records then from ToDoList it does not go to Info but throws exception and I see it's going to ToDoListSelect which is weird. I do not know where to start looking for the problem. Any suggestions? Any details needed just let me know.
Here are the routes in my application:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( "Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
The error thrown is:
Server Error in '/' Application.
The operation is invalid because of the current state of the object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about this error, view and determine where the error originated in the code.
Exception Details: System.InvalidOperationException: Operation is not valid due to the current state of the object.
Source Error:
During execution of the current web request An unhandled exception was generated. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
[InvalidOperationException: Der Vorgang ist aufgrund des aktuellen Zustands des Objekts ungültig.]
System.Web.HttpRequest.FillInFormCollection() +11485999
System.Web.HttpRequest.get_Form() +157
Microsoft.Web.Infrastructure.DynamicValidationHelper.<>c__DisplayClass12.<ReplaceCollection>b__e() +63
Microsoft.Web.Infrastructure.DynamicValidationHelper.<>c__DisplayClass12.<ReplaceCollection>b__11() +20
Microsoft.Web.Infrastructure.DynamicValidationHelper.DeferredCountArrayList.get_Count() +20
System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +34
System.Web.HttpRequest.get_Form() +212
System.Web.Mvc.FormValueProvider..ctor(ControllerContext controllerContext, IUnvalidatedRequestValues unvalidatedValues) +55
System.Web.Mvc.FormValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +61
System.Web.Mvc.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) +28
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +238
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +148
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +472
System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +347
System.Web.Mvc.ControllerBase.get_ValueProvider() +46
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +80
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +153
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +691
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +305
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
Figured it out! Thanks Mr. Google!
http://geekswithblogs.net/renso/archive/2012/01/19/operation-is-not-valid-due-to-the-current-state-of.aspx
Put the change in web.config and it works fine.

Resources