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

发布于 2024-08-03 13:59:55 字数 1262 浏览 3 评论 0原文

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 的“Pro ASP.NET MVC Framework”一书。在第 132 页,根据作者的推荐,我下载了 ASP.NET MVC Futures 程序集,并将其添加到我的 MVC 项目中。 [注意:这可能是一个转移注意力的事情。]

此后,我无法再加载我的项目。上面的错误让我愣住了。

我的问题是不是,“你能帮我修复我的代码吗?”

相反,我想更广泛地了解:

  • 我应该如何解决这个问题?
  • 我应该寻找什么?
  • 根本原因可能是什么?

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

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:         }

I was following Steven Sanderson's 'Pro ASP.NET MVC Framework' book. On page 132, in accordance with the author's recommendation, I downloaded the ASP.NET MVC Futures assembly, and added it to my MVC project. [Note: This could be a red herring.]

After this, I could no longer load my project. The above error stopped me cold.

My question is not, "Could you help me fix my code?"

Instead, I'd like to know more generally:

  • How should I troubleshoot this issue?
  • What should I be looking for?
  • What might the root cause be?

It seems like I should understand routing and controllers at a deeper level than I do now.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

爱人如己 2024-08-10 13:59:55

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

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

System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext 控制器上下文,ModelBindingContext 绑定上下文,类型 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
    {
    }
}

I just had a similar problem. The same exception occurs when a Model has no parameterless constructor.

The call stack was figuring a method responsible for creating a new instance of a model.

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


Here is a sample:

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
    {
    }
}
此生挚爱伱 2024-08-10 13:59:55

如果您的模型使用 SelectList,也可能会导致这种情况,因为它没有无参数构造函数

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

如果这是原因,您需要重构模型以采用不同的方式执行此操作。因此,使用 IEnumerable 并编写一个扩展方法来创建具有不同属性定义的下拉列表:

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; }
    }

This can also be caused if your Model is using a SelectList, as this has no parameterless constructor:

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

You'll need to refactor your model to do it a different way if this is the cause. So using an IEnumerable<Contact> and writing an extension method that creates the drop down list with the different property definitions:

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(..)
}

Or you can use the @Mark and @krilovich approach, just need replace SelectList to IEnumerable, it's works with MultiSelectList too.

 public class MyViewModel
    {
        public Contact SelectedContact { get;set; }
        public IEnumerable<SelectListItem> Contacts { get;set; }
    }
哆啦不做梦 2024-08-10 13:59:55

您需要与控制器对应的操作不具有参数。

看起来像您拥有的控制器/操作组合:

public ActionResult Action(int parameter)
{

}

但您

public ActionResult Action()
{

}

还需要查看 Phil Haack 的 路由调试器 用于排除路由故障。

You need the action that corresponds to the controller to not have a parameter.

Looks like for the controller / action combination you have:

public ActionResult Action(int parameter)
{

}

but you need

public ActionResult Action()
{

}

Also, check out Phil Haack's Route Debugger to troubleshoot routes.

暗喜 2024-08-10 13:59:55

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

public MyController() : this(new Helper()) {
}

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

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

这允许您将依赖注入框架与 MVC 结合使用,并真正解耦一切。 StructureMap 网站 就是一个很好的示例。整个快速入门很好,他在“Auto Wiring”的底部详细介绍了 MVC。

By default, MVC Controllers require a default constructor with no parameters. The simplest would be to make a default constructor that calls the one with parameters:

public MyController() : this(new Helper()) {
}

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

However, you can override this functionality by rolling your own ControllerFactory. This way you can tell MVC that when you are creating a MyController give it an instance of Helper.

This allows you to use Dependency Injection frameworks with MVC, and really decouple everything. A good example of this is over at the StructureMap website. The whole quickstart is good, and he gets specific to MVC towards the bottom at "Auto Wiring".

晨敛清荷 2024-08-10 13:59:55

使用 IDependencyResolver,例如使用 IoC 容器时,依赖解析器返回 null。在这种情况下,ASP.NET MVC 3 默认使用 DefaultControllerActivator 来创建对象。如果正在创建的对象没有公共无参数构造函数,则只要提供的依赖解析器返回 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

This error also occurs when using an IDependencyResolver, such as when using an IoC container, and the dependency resolver returns null. In this case ASP.NET MVC 3 defaults to using the DefaultControllerActivator to create the object. If the object being created does not have a public no-args constructor an exception will then be thrown any time the provided dependency resolver has returned null.

Here's one such stack trace:

[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
晒暮凉 2024-08-10 13:59:55

您可以在 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 中的其他扩展点编写类似的代码(例如控制器构造)。

You can get this exception at many different places in the MVC framework (e.g. it can't create the controller, or it can't create a model to give that controller).

The only easy way I've found to diagnose this problem is to override MVC as close to the exception as possible with your own code. Then your code will break inside Visual Studio when this exception occurs, and you can read the Type causing the problem from the stack trace.

This seems like a horrible way to approach this problem, but it's very fast, and very consistent.

For example, if this error is occurring inside the MVC DefaultModelBinder (which you will know by checking the stack trace), then replace the DefaultModelBinder with this code:

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);
    }
}

And update your Global.asax.cs:

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

Now the next time you get that exception, Visual Studio will stop inside your MyDefaultModelBinder class, and you can check the "modelType" property to see what type caused the problem.

The example above works for when you get the "No parameterless constructor defined for this object" exception during model binding, only. But similar code can be written for other extension points in MVC (e.g. controller construction).

叹倦 2024-08-10 13:59:55

我遇到了同样的错误,我的例子中的罪魁祸首是构造函数,它既不是公共的也不是私有的

没有为此对象定义无参数构造函数。

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

重现代码:确保构造函数前面有 public。

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

    public string name
    {
        get;
        set;
    }
}

I got the same error, the culprit in my case was the constructor which was neither public nor private.

No parameterless constructor defined for this object.

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Repro code: Make sure the constructor has public before it.

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

    public string name
    {
        get;
        set;
    }
}
别把无礼当个性 2024-08-10 13:59:55

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

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

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

问题在于接口依赖性。

First video on http://tekpub.com/conferences/mvcconf

47:10 minutes in show the error and shows how to override the default ControllerFactory.
I.e. to create structure map controller factory.

Basically, you are probably trying to implement dependency injection??

The problem is that is the interface dependency.

千秋岁 2024-08-10 13:59:55

当使用自定义 ModelView时,我遇到了相同的错误

,两个操作(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)
{...}

问题是视图收到了 ModelView(需要产品和类别信息列表),但提交后仅返回 Product 对象,但由于 POST Add 期望 ProductModelView 它传递了 NULL,但 ProductModelView 仅构造函数需要两个参数(Product、RootCategories),然后它尝试查找另一个构造函数如果这个 NULL 情况没有参数,则失败并显示“无参数...”

因此,按如下方式修复 POST Add 可以纠正问题:

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

希望这可以帮助某人(我花了将近半天的时间才找到这个问题!)。

I got the same error when:

Using a custom ModelView, both Actions (GET and POST) were passing the ModelView that contained two objects:

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

And the POST also accepting the same model view:

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

Problem was the View received the ModelView (needed both product and list of categories info), but after submitted was returning only the Product object, but as the POST Add expected a ProductModelView it passed a NULL but then the ProductModelView only constructor needed two parameters(Product, RootCategories), then it tried to find another constructor with no parameters for this NULL case then fails with "no parameterles..."

So, fixing the POST Add as follows correct the problem:

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

Hope this can help somebody (I spent almost half day to find this out!).

九公里浅绿 2024-08-10 13:59:55

对我来说也一样。
我的问题出现是因为我忘记了我的基模型类已经具有视图中定义的名称的属性

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 请求出现“无参数构造函数”错误。

希望有帮助。

The same for me.
My problem appeared because i forgot that my 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  { ... }

... and controller processing model :

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

Nothing special, right? But then i define the view ...

<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>

... which causes "Parameterless constructor" error on POST request.

Hope that helps.

泛滥成性 2024-08-10 13:59:55

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

即使提供了除一个之外的所有参数,并且即使缺少一个可为 null 的类型,也会出现此问题。

该问题也可能是由于拼写错误造成的,其中参数名称和表单字段的名称不相同。

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

I had a similar problem, and basically the point is that there are some arguments in the action method that were not supplied by the Model Binding process, (and in other words these fields were not submitted by the submitting page).

This problem will come up even if all arguments but one are supplied, and even if the one missing is a nullable type.

The problem might also be a result of a typo, in which the name of the argument and name of the form field will not be identical.

The solution is to 1) verify that the names match up 2) provide a default value for the argument 3) or provide another action method without this argument.

执手闯天涯 2024-08-10 13:59:55

我也遇到了这个问题,并认为我会分享,因为我在上面找不到我的问题。

这是我的代码

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

调用此 ActionResult:

public ActionResult Overview(int id)

我认为它足够聪明,可以计算出发现我传递给它的值是 Overview 的 id 参数,但事实并非如此。这修复了它:

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

I had this problem as well and thought I'd share since I can't find my problem above.

This was my code

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

Calling this ActionResult:

public ActionResult Overview(int id)

I assumed it would be smart enough to figure out that the value I pass it is the id paramter for Overview, but it's not. This fixed it:

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

夜血缘 2024-08-10 13:59:55

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

代码如下:

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

更改为

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

问题已解决。

I got same exception due to there was no parameterless public contructor

Code was like this:

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

changed to

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

problem resolved to me.

滥情哥ㄟ 2024-08-10 13:59:55

所有答案都说创建一个无参数构造函数,如果您不希望任何其他开发人员使用它而只使用模型绑定器,那么这并不理想。

如果另一个开发人员尝试使用公共构造函数上方的属性 [Obsolete("For model binding only", true)] 将引发编译器错误。我花了很长时间才找到这个,希望它对某人有所帮助。

All of the answers say to create a parameters less constructor which isn't ideal if you don't want any other devs using it and only the model binder.

The attribute [Obsolete("For model binding only", true)] above a public constructor will throw a compiler error if another dev tries to use this. Took me ages to find this, hope it helps someone.

黎歌 2024-08-10 13:59:55

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

I got this error. I was using interfaces in my constructor and my dependency resolver wasn't able to resolve, when i registered it then the error went away.

平生欢 2024-08-10 13:59:55

我遇到了同样的问题...

如果您使用接口来解耦与 DbContext 的连接(像我一样),您可以使用 structuralmap.mvc (3 或 4 - nudget 包) 能够在控制器类中使用结构。这将为您提供一个 DependencyResolution 文件夹。只需用 For< 更改注释行即可InterfaceClass >() 和 Use< DbContextClass > ()。

I had the same problem...

If your using a interface to decouple your connection against your DbContext (like me) you can use structuremap.mvc (3 or 4 - nudget package) to be able to use a constructure in your controller class. This will give you a DependencyResolution folder. Just change the commented line with your For< InterfaceClass >() and to Use< DbContextClass >().

懒猫 2024-08-10 13:59:55

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

While this may be obvious to some, the culprit of this error for me was my MVC method was binding to a model that contained a property of type Tuple<>. Tuple<> has no parameterless constructor.

北方的韩爷 2024-08-10 13:59:55

由于缺少依赖项注入器/解析器容器和/或缺少绑定,可能会出现此类型错误

  1. 使用 NugetPacketManager(Unity、Ninject 或您喜欢的任何一个)将依赖项注入器添加到您的项目中 添加接口的
  2. 绑定和类的具体实现

UnityMConfig.cs

using System;
using Unity;
using <your_namespace for the interfaces and concrete classes>

namespace <your_namespace>
{
    public static class UnityConfig
    {
        private static Lazy<IUnityContainer> container =
            new Lazy<IUnityContainer>(() =>
            {
                var container = new UnityContainer();
                RegisterTypes(container);
                return container;
            });

        public static IUnityContainer Container => container.Value;

        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType <IInterfaceClassName, ConcreteImplementationOfInterface> ();
        }
    }
}

UnityMvcActivator.cs

using System.Linq;
using System.Web.Mvc;
using Unity.AspNet.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(xxxx.UnityMvcActivator), nameof(xxxx.UnityMvcActivator.Start))]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(xxxx.UnityMvcActivator), nameof(xxxx.UnityMvcActivator.Shutdown))]

namespace <your_namespace>
{
    public static class UnityMvcActivator
    {
        public static void Start()
        {
            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));
            DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));
        }
        public static void Shutdown()
        {
            UnityConfig.Container.Dispose();
        }
    }
}

This type error may come up due to missing dependency injector/resolver container and/or missing the bindings

  1. Add Dependency injector to your project using NugetPacketManager (Unity, Ninject or whichever you like)
  2. Add binding(s) for interface and concrete implementation for the classes

UnityMConfig.cs

using System;
using Unity;
using <your_namespace for the interfaces and concrete classes>

namespace <your_namespace>
{
    public static class UnityConfig
    {
        private static Lazy<IUnityContainer> container =
            new Lazy<IUnityContainer>(() =>
            {
                var container = new UnityContainer();
                RegisterTypes(container);
                return container;
            });

        public static IUnityContainer Container => container.Value;

        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType <IInterfaceClassName, ConcreteImplementationOfInterface> ();
        }
    }
}

UnityMvcActivator.cs

using System.Linq;
using System.Web.Mvc;
using Unity.AspNet.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(xxxx.UnityMvcActivator), nameof(xxxx.UnityMvcActivator.Start))]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(xxxx.UnityMvcActivator), nameof(xxxx.UnityMvcActivator.Shutdown))]

namespace <your_namespace>
{
    public static class UnityMvcActivator
    {
        public static void Start()
        {
            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));
            DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));
        }
        public static void Shutdown()
        {
            UnityConfig.Container.Dispose();
        }
    }
}
夏末的微笑 2024-08-10 13:59:55

我遇到了同样的问题,但后来发现添加任何新接口和相应的类都需要将其注册在可初始化模块下以进行依赖项注入。就我而言,它的内部代码如下:

[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)
    {
    }
}

}

I had same problem but later found adding any new interface and corresponding class requires it to be registered under Initializable Module for dependency injection. In my case it was inside code as follows:

[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)
    {
    }
}

}

失眠症患者 2024-08-10 13:59:55

就我而言,我的类具有 [Serializable] 属性。

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

In my case, my class had the [Serializable] attribute.

You are required to have a constructor that takes no parameters if your class is [Serializable]

作妖 2024-08-10 13:59:55

我向 DOMAIN 文件夹内的模型添加了一个无参数构造函数,问题得到了解决。

在此处输入图像描述

 public User()
        {

        }

I added a parameterless constructor to the model inside of DOMAIN Folder, and the problem is solved.

enter image description here

 public User()
        {

        }
明媚殇 2024-08-10 13:59:55

当尝试在 DbContext 类上添加迁移时,我遇到了同样的问题。

首先,我收到错误:无法创建“ContextDb”类型的对象。有关设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink /?linkid=851728

这让我添加了接口 IDesignTimeDbContextFactory 并实现了它的功能:

public ContextDb CreateDbContext(string[] args)
    {
        var optionBuilder = new DbContextOptionsBuilder<ContextDb>();
        optionBuilder.UseSqlServer("Server_connection");
        return new ContextDb(optionBuilder.Options);
    }

此时再次尝试 Add-Migration 时出现错误 Noparameterlessconstructor Defined for type 'LibraryContext.ContextDb' 。这是由于在 CreateDbContext() 中创建了 ContextDb 的新实例而发生的。
为了解决这个问题,我只是添加了一个空的构造函数:

public ContextDb()     
    {
    }

I got the same issue when trying to Add-Migration on the DbContext class.

First I got the error: Unable to create an object of type 'ContextDb'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Which made me add the interface IDesignTimeDbContextFactory and implement it's function:

public ContextDb CreateDbContext(string[] args)
    {
        var optionBuilder = new DbContextOptionsBuilder<ContextDb>();
        optionBuilder.UseSqlServer("Server_connection");
        return new ContextDb(optionBuilder.Options);
    }

At this time the error No parameterless constructor defined for type 'LibraryContext.ContextDb' happened when trying to Add-Migration again. Which occured due to the new instance of the ContextDb created in CreateDbContext().
To fix this I just added an empty constructor:

public ContextDb()     
    {
    }
∞觅青森が 2024-08-10 13:59:55

当我添加一种新的方法来实例化类时,这个错误就开始出现了。

示例:

    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;
         }
     }

This error started for me when I added a new way to instantiate a class.

Example:

    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;
         }
     }

The error was resolved when I added when I made this change, adding a parameterless constructor. I believe the compiler creates a parameterless constuctor by default but if you add your own then you must explicitly create it.

    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;
         }
     }
不如归去 2024-08-10 13:59:55

我已在表单中添加了一个 DropDownList ,但就我而言,它没有(也无意)与表单一起提交,因为它位于

之外;

标签:

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

由于 Model 包含仅用于显示的字段,这也会导致 Noparameterlessconstructordefineforthisobject 错误,因为该字段根本没有提交。

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

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

I'd added a DropDownList to my form, however in my case it wasn't (and wasn't intended to be) submitted with the form as it was outside of the <form></form> tags:

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

As the Model contained the field for display only, this also caused the No parameterless constructor defined for this object error because the field wasn't submitted at all.

In this case I fixed it by adding an exclude binding:

public ActionResult Foo(int id, int? page, [Bind(Exclude = "MyField")]MyModel model)
流星番茄 2024-08-10 13:59:55

这发生在我身上,这个页面上的结果是一个很好的资源,引导我走向很多方向,但我想添加另一种可能性:

正如其他回复中所述,创建带参数的构造函数会删除隐式无参数构造函数,因此您必须明确键入它。

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

给出错误:

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

有效:

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

This happened to me, and the results on this page were a good resource that led me in many directions, but I would like to add another possibility:

As stated in other replies, creating a constructor with parameters removes the implicit parameterless constructor, so you have to explicitly type it.

What was my problem was that a constructor with default parameters also triggered this exception.

Gives errors:

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

Works:

public CustomerWrapper(CustomerDto customer){...}
public CustomerWrapper():this(null){}
來不及說愛妳 2024-08-10 13:59:55

最有可能的是,您的控制器中可能有参数化构造函数,并且您使用的任何依赖项解析器都无法正确解析依赖项。您需要在编写依赖解析器方法的位置放置断点,然后您将在内部异常中得到确切的错误。

Most probably you might have parameterized constructor in your controller and whatever dependency resolver you are using is not able to resolve the dependency properly. You need to put break-point where the dependency resolver method is written and you will get the exact error in inner exception.

皓月长歌 2024-08-10 13:59:55

我也有同样的问题。

刚刚从 Post Action 方法参数中删除了 HttpFileCollectionBase files
并在方法主体中添加类似 HttpFileCollectionBase files = Request.Files; 的内容。

I had the same problem.

Just Removed HttpFileCollectionBase files from Post Action method argument
and added like HttpFileCollectionBase files = Request.Files; in method body.

ゞ花落谁相伴 2024-08-10 13:59:55

所以我之前在进行 ajax 调用时也收到过该消息。所以它基本上要求的是控制器调用的模型类中的构造函数,没有任何参数。

这是一个例子

public class MyClass{

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

 }

So I have gotten that message before as well, when doing an ajax call. So what it's basically asking for is a constructor in that model class that is being called by the contoller, doesn't have any parameter.

Here is an example

public class MyClass{

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

 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文