首页 文章

ASP.NET MVC:没有为此对象定义的无参数构造函数

提问于
浏览
158
Server Error in '/' Application.
--------------------------------------------------------------------------------

No parameterless constructor defined for this object. 
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.MissingMethodException: No parameterless constructor defined for this object.

Source Error: 


Line 16:             HttpContext.Current.RewritePath(Request.ApplicationPath, false);
Line 17:             IHttpHandler httpHandler = new MvcHttpHandler();
Line 18:             httpHandler.ProcessRequest(HttpContext.Current);
Line 19:             HttpContext.Current.RewritePath(originalPath, false);
Line 20:         }

我正在关注Steven Sanderson 's ' Pro ASP.NET MVC Framework ' book. On page 132, in accordance with the author'的推荐,我下载了ASP.NET MVC Futures程序集,并将其添加到我的MVC项目中 . [注意:这可能是一个红鲱鱼 . ]

在此之后,我无法再加载我的项目 . 上面的错误阻止了我 .

我的问题是 not ,"Could you help me fix my code?"

相反,我想更全面地了解:

  • 如何解决此问题?

  • 我应该寻找什么?

  • 根本原因可能是什么?

看起来我应该比现在更深入地了解路由和控制器 .

25 回答

  • 6

    虽然这对某些人来说可能是显而易见的,但这个错误的罪魁祸首是我的MVC方法绑定到包含 Tuple<> 类型属性的模型 . Tuple<> 没有无参数构造函数 .

  • 16

    我刚遇到类似的问题 . 当 Model 没有无参数构造函数时,会发生相同的异常 .

    调用堆栈正在计算一个负责创建模型新实例的方法 .

    System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext,Type modelType)


    这是一个示例:

    public class MyController : Controller
    {
        public ActionResult Action(MyModel model)
        {
    
        }
    }
    
    public class MyModel
    {
        public MyModel(IHelper helper) // MVC cannot call that
        {
            // ...
        }
    
        public MyModel() // MVC can call that
        {
        }
    }
    
  • 13

    如果您的模型使用SelectList, as this has no parameterless constructor 也可能导致此问题:

    public class MyViewModel
    {
        public SelectList Contacts { get;set; }
    }
    

    如果这是原因,你需要重构你的模型以不同的方式做 . 所以使用 IEnumerable<Contact> 并编写一个扩展方法,创建具有不同属性定义的下拉列表:

    public class MyViewModel
    {
        public Contact SelectedContact { get;set; }
        public IEnumerable<Contact> Contacts { get;set; }
    }
    
    public static MvcHtmlString DropDownListForContacts(this HtmlHelper helper, IEnumerable<Contact> contacts, string name, Contact selectedContact)
    {
        // Create a List<SelectListItem>, populate it, return DropDownList(..)
    }
    

    或者您可以使用@Mark和@krilovich方法,只需要将SelectList替换为IEnumerable,它也适用于MultiSelectList .

    public class MyViewModel
        {
            public Contact SelectedContact { get;set; }
            public IEnumerable<SelectListItem> Contacts { get;set; }
        }
    
  • 22

    您需要与控制器对应的操作没有参数 .

    看起来你有控制器/动作组合:

    public ActionResult Action(int parameter)
    {
    
    }
    

    但你需要

    public ActionResult Action()
    {
    
    }
    

    另外,请查看Phil Haack的Route Debugger以排除路线故障 .

  • 2

    默认情况下,MVC控制器需要一个没有参数的默认构造函数 . 最简单的方法是创建一个默认构造函数来调用带参数的构造函数:

    public MyController() : this(new Helper()) {
    }
    
    public MyController(IHelper helper) {
      this.helper = helper;
    }
    

    但是,您可以通过滚动自己的 ControllerFactory 来覆盖此功能 . 通过这种方式,您可以告诉MVC在创建 MyController 时为其提供 Helper 的实例 .

    这允许您将依赖注入框架与MVC一起使用,并真正解耦所有内容 . 一个很好的例子就是StructureMap website . 整个快速入门是好的,他在"Auto Wiring"对MVC的底部有所了解 .

  • 0

    使用IDependencyResolver时也会发生此错误,例如使用IoC容器时,依赖项解析程序返回null . 在这种情况下,ASP.NET MVC 3默认使用DefaultControllerActivator来创建对象 . 如果正在创建的对象没有公共的no-args构造函数,则只要提供的依赖项解析程序返回null,就会抛出异常 .

    这是一个这样的堆栈跟踪:

    [MissingMethodException: No parameterless constructor defined for this object.]
       System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
       System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
       System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
       System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
       System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67
    
    [InvalidOperationException: An error occurred when trying to create a controller of type 'My.Namespace.MyController'. Make sure that the controller has a parameterless public constructor.]
       System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
       System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
       System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
       System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
       System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
       System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
       System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
       System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
       System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
       System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
       System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
       System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963444
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
    
  • 2

    所有答案都说创建一个参数较少的构造函数,如果您不希望任何其他开发人员使用它而只需要模型 Binders ,这是不理想的 .

    如果另一个开发人员尝试使用此属性,则公共构造函数上方的属性 [Obsolete("For model binding only", true)] 将抛出编译器错误 . 花了我很多年才找到这个,希望它有助于某人 .

  • 0

    我收到了这个错误 . 我在我的构造函数中使用接口,我的依赖解析器无法解析,当我注册它然后错误消失了 .

  • 0

    您可以在MVC框架中的许多不同位置获取此异常(例如,它无法创建控制器,或者无法创建模型来提供该控制器) .

    我发现诊断此问题的唯一简单方法是使用您自己的代码覆盖尽可能接近异常的MVC . 然后,当发生此异常时,您的代码将在Visual Studio内部中断,并且您可以从堆栈跟踪中读取导致问题的类型 .

    这似乎是解决这个问题的可怕方法,但它非常快,而且非常一致 .

    例如,如果在MVC DefaultModelBinder内部发生此错误(您将通过检查堆栈跟踪来了解),则使用以下代码替换DefaultModelBinder:

    public class MyDefaultModelBinder : System.Web.Mvc.DefaultModelBinder
    {
        protected override object CreateModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, Type modelType)
        {
            return base.CreateModel(controllerContext, bindingContext, modelType);
        }
    }
    

    并更新您的Global.asax.cs:

    public class MvcApplication : System.Web.HttpApplication
    {
    ...
        protected void Application_Start(object sender, EventArgs e)
        {
            ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder();
        }
    }
    

    现在,下次出现异常时,Visual Studio将停止在MyDefaultModelBinder类中,您可以检查“modelType”属性以查看导致问题的类型 .

    上面的示例适用于仅在模型绑定期间获得“为此对象定义的无参数构造函数”异常时 . 但是可以为MVC中的其他扩展点编写类似的代码(例如,控制器构造) .

  • 84

    我得到了同样的错误,我的案例中的罪魁祸首是 was neither public nor private 的构造函数 .

    没有为此对象定义无参数构造函数 . 异常详细信息:System.MissingMethodException:没有为此对象定义的无参数构造函数 .

    Repro代码:确保构造函数在它之前已公开 .

    public class Chuchi()
    {
         Chuchi()    // The problem is this line. Public is missing
         {
             // initialization
             name="Tom Hanks";
         }
    
        public string name
        {
            get;
            set;
        }
    }
    
  • 207

    http://tekpub.com/conferences/mvcconf上的第一个视频

    47:10分钟显示错误并显示如何覆盖默认的ControllerFactory . 即创建结构图控制器工厂 .

    基本上,您可能正在尝试实现依赖注入?

    问题是接口依赖性 .

  • -3

    我遇到同样的错误:

    使用自定义ModelView,两个Actions(GET和POST)都传递包含两个对象的ModelView:

    public ActionResult Add(int? categoryID)
    {
        ...
        ProductViewModel productViewModel = new ProductViewModel(
                product,
                rootCategories
                );
        return View(productViewModel); 
    }
    

    POST也接受相同的模型视图:

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Add(ProductModelView productModelView)
    {...}
    

    问题是View收到了ModelView(需要产品和类别信息列表),但是在提交后只返回Product对象,但是作为POST Add期望一个ProductModelView它传递了一个NULL但是ProductModelView只有构造函数需要两个参数(产品,RootCategories),然后它试图找到另一个没有参数的构造函数用于这个NULL情况然后失败并带有“no parameterles ...”

    因此,修复POST Add如下更正问题:

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Add(Product product)
    {...}
    

    希望这可以帮助别人(我花了差不多半天才发现这个!) .

  • 4

    我也一样 . 我的问题出现了,因为我忘记了我的 base model class already has property with the name which was defined in the view .

    public class CTX : DbContext {  // context with domain models
        public DbSet<Products> Products { get; set; }  // "Products" is the source property
        public CTX() : base("Entities") {}
    }
    
    public class BaseModel : CTX { ... }
    public class ProductModel : BaseModel { ... }
    public class OrderIndexModel : OrderModel  { ... }
    

    ...和控制器处理模型:

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Index(OrderIndexModel order) { ... }
    

    没什么特别的吧?但后来我定义了视图......

    <div class="dataItem">
        <%=Html.Label("Products")%>
        <%=Html.Hidden("Products", Model.index)%>   // I FORGOT THAT I ALREADY HAVE PROPERTY CALLED "Products"
        <%=Html.DropDownList("ProductList", Model.products)%>
        <%=Html.ActionLink("Delete", "D")%>
    </div>
    

    ...在POST请求中导致“无参数构造函数”错误 .

    希望有所帮助 .

  • 7

    我有一个类似的问题,基本上重点是动作方法中有一些参数不是由模型绑定过程提供的(换句话说,这些字段不是由提交页面提交的) .

    即使提供了除一个参数之外的所有参数,即使缺少的参数是可空类型,也会出现此问题 .

    问题也可能是拼写错误的结果,其中参数的名称和表单字段的名称将不相同 .

    解决方案是1)验证名称是否匹配2)为参数提供默认值3)或提供不带此参数的另一个操作方法 .

  • 0

    我也遇到过这个问题并且认为我会分享,因为我无法找到上面的问题 .

    这是我的代码

    return RedirectToAction("Overview", model.Id);

    调用此ActionResult:

    public ActionResult Overview(int id)

    我认为它足够聪明,可以弄清楚我传递的值是概述的id参数,但事实并非如此 . 这解决了它:

    return RedirectToAction("Overview", new {id = model.Id});

  • 0

    由于没有无参数的公共构造函数,我得到了相同的异常

    代码是这样的:

    public class HomeController : Controller
    {        
        private HomeController()
        {
            _repo = new Repository();
        }
    

    changed to

    public class HomeController : Controller
    {        
        public HomeController()
        {
            _repo = new Repository();
        }
    

    问题解决了我 .

  • 5

    我有同样的问题...

    如果您使用接口将连接与DbContext(像我一样)分离,则可以使用 structuremap.mvc (3或4 - nudget包)来在控制器类中使用constructure . 这将为您提供DependencyResolution文件夹 . 只需使用For <InterfaceClass>()更改注释行,然后使用<DbContextClass>() .

  • 0

    当我添加一种实例化类的新方法时,这个错误开始了 .

    例:

    public class myClass
        {
             public string id{ get; set; }
             public List<string> myList{get; set;}
    
             // error happened after I added this
             public myClass(string id, List<string> lst)
             {
                 this.id= id;
                 this.myList= lst;
             }
         }
    

    当我在进行此更改时添加无参数构造函数时添加了错误 . 我相信默认情况下编译器会创建一个无参数构造函数,但如果添加自己的构造函数,则必须显式创建它 .

    public class myClass
        {
             public string id{ get; set; }
             public List<string> myList{get; set;}
    
             // error doesn't happen when I add this
             public myClass() { }
    
             // error happened after I added this, but no longer happens after adding above
             public myClass(string id, List<string> lst)
             {
                 this.id= id;
                 this.myList= lst;
             }
         }
    
  • 0

    我在我的表单中添加了一个 DropDownList ,但在我的情况下,它不是't (and wasn' t意图提交的表单,因为它在 <form></form> 标签之外:

    @Html.DropDownList("myField", Model.MyField)
    

    由于模型仅包含要显示的字段,因此也会导致 No parameterless constructor defined for this object 错误,因为该字段根本未提交 .

    在这种情况下,我通过添加排除绑定来修复它:

    public ActionResult Foo(int id, int? page, [Bind(Exclude = "MyField")]MyModel model)
    
  • 5

    这发生在我身上,这个页面上的结果是一个很好的资源,导致我在很多方面,但我想补充另一种可能性:

    如其他回复中所述,使用参数创建构造函数会删除隐式无参数构造函数,因此你必须明确键入它 .

    我的问题是,具有默认参数的构造函数也触发了此异常 .

    给出错误:

    public CustomerWrapper(CustomerDto customer = null){...}
    

    作品:

    public CustomerWrapper(CustomerDto customer){...}
    public CustomerWrapper():this(null){}
    
  • 1

    很可能您可能在控制器中有参数化构造函数,并且您正在使用的依赖项解析器无法正确解析依赖项 . 您需要将断点放在写入依赖项解析器方法的位置,并且您将在内部异常中获得确切的错误 .

  • 20

    我有同样的问题,但后来发现添加任何新的接口和相应的类要求它在Initializable模块下注册依赖注入 . 在我的情况下,内部代码如下:

    [InitializableModule]
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class DependencyResolverInitialization : IConfigurableModule
    {
    
        public void ConfigureContainer(ServiceConfigurationContext context)
        {
            context.Container.Configure(ConfigureContainer);
            var structureMapDependencyResolver = new StructureMapDependencyResolver(context.Container);
            DependencyResolver.SetResolver(structureMapDependencyResolver);
            GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), structureMapDependencyResolver);
        }
    
        private void ConfigureContainer(ConfigurationExpression container)
        {
            container.For<IAppSettingService>().Use<AppSettingService>();
            container.For<ISiteSettingService>().Use<SiteSettingService>();
            container.For<IBreadcrumbBuilder>().Use<BreadcrumbBuilder>();
            container.For<IFilterContentService>().Use<FilterContentService>().Singleton();
            container.For<IDependecyFactoryResolver>().Use<DependecyFactoryResolver>();
            container.For<IUserService>().Use<UserService>();
            container.For<IGalleryVmFactory>().Use<GalleryVmFactory>();
            container.For<ILanguageService>().Use<LanguageService>();
            container.For<ILanguageBranchRepository>().Use<LanguageBranchRepository>();
            container.For<ICacheService>().Use<CacheService>(); 
            container.For<ISearchService>().Use<SearchService>();
            container.For<IReflectionService>().Use<ReflectionService>();
            container.For<ILocalizationService>().Use<LocalizationService>();
            container.For<IBookingFormService>().Use<BookingFormService>();
            container.For<IGeoService>().Use<GeoService>();
            container.For<ILocationService>().Use<LocationService>();
            RegisterEnterpriseAPIClient(container);
        }
    
       public void Initialize(InitializationEngine context)
        {
        }
    
        public void Uninitialize(InitializationEngine context)
        {
        }
    
        public void Preload(string[] parameters)
        {
        }
    }
    

    }

  • 2

    我有同样的问题 .

    刚从Post Action方法参数中删除了 HttpFileCollectionBase files ,并在方法体中添加了 HttpFileCollectionBase files = Request.Files; .

  • 8

    就我而言,我的 class 有 [Serializable] 属性 .

    如果您的类是 [Serializable] ,则需要一个不带参数的构造函数

  • 4

    所以我在做ajax调用之前也收到了这条消息 . 所以它基本上要求的是该模型类中由构造函数调用的构造函数,它没有任何参数 .

    这是一个例子

    public class MyClass{
    
         public MyClass(){} // so here would be your parameterless constructor
    
     }
    

相关问题