ASP.NET 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: }
我正在关注 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
我刚刚遇到了类似的问题。当
Model
没有无参数构造函数时,也会发生相同的异常。调用堆栈正在计算负责创建模型的新实例的方法。
这是一个示例:
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.
Here is a sample:
如果您的模型使用 SelectList,也可能会导致这种情况,因为它没有无参数构造函数:
如果这是原因,您需要重构模型以采用不同的方式执行此操作。因此,使用
IEnumerable
并编写一个扩展方法来创建具有不同属性定义的下拉列表:或者您可以使用 @Mark 和 @krilovich 方法,只需将 SelectList 替换为 IEnumerable,它也适用于 MultiSelectList。
This can also be caused if your Model is using a SelectList, as this has no parameterless constructor:
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:Or you can use the @Mark and @krilovich approach, just need replace SelectList to IEnumerable, it's works with MultiSelectList too.
您需要与控制器对应的操作不具有参数。
看起来像您拥有的控制器/操作组合:
但您
还需要查看 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:
but you need
Also, check out Phil Haack's Route Debugger to troubleshoot routes.
默认情况下,MVC 控制器需要一个不带参数的默认构造函数。最简单的方法是创建一个默认构造函数来调用带参数的构造函数:
但是,您可以通过滚动自己的
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:
However, you can override this functionality by rolling your own
ControllerFactory
. This way you can tell MVC that when you are creating aMyController
give it an instance ofHelper
.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".
使用 IDependencyResolver,例如使用 IoC 容器时,依赖解析器返回 null。在这种情况下,ASP.NET MVC 3 默认使用 DefaultControllerActivator 来创建对象。如果正在创建的对象没有公共无参数构造函数,则只要提供的依赖解析器返回 null,就会抛出异常。
这是一个这样的堆栈跟踪:
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:
您可以在 MVC 框架中的许多不同位置获得此异常(例如,它无法创建控制器,或者无法创建模型来提供该控制器)。
我发现诊断此问题的唯一简单方法是使用您自己的代码尽可能接近异常地覆盖 MVC。然后,当发生此异常时,您的代码将在 Visual Studio 内部中断,并且您可以从堆栈跟踪中读取导致问题的类型。
这似乎是解决这个问题的一种可怕的方法,但它非常快,而且非常一致。
例如,如果此错误发生在 MVC DefaultModelBinder 内部(您可以通过检查堆栈跟踪知道),则用以下代码替换 DefaultModelBinder:
并更新您的 Global.asax.cs:
现在,下次您收到该异常时, 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:
And update your Global.asax.cs:
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).
我遇到了同样的错误,我的例子中的罪魁祸首是构造函数,它既不是公共的也不是私有的。
重现代码:确保构造函数前面有 public。
I got the same error, the culprit in my case was the constructor which was neither public nor private.
Repro code: Make sure the constructor has public before it.
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.
当使用自定义 ModelView时,我遇到了相同的错误
,两个操作(GET 和 POST)都传递包含两个对象的 ModelView:
并且 POST 也接受相同的模型视图:
问题是视图收到了 ModelView(需要产品和类别信息列表),但提交后仅返回 Product 对象,但由于 POST Add 期望 ProductModelView 它传递了 NULL,但 ProductModelView 仅构造函数需要两个参数(Product、RootCategories),然后它尝试查找另一个构造函数如果这个 NULL 情况没有参数,则失败并显示“无参数...”
因此,按如下方式修复 POST Add 可以纠正问题:
希望这可以帮助某人(我花了将近半天的时间才找到这个问题!)。
I got the same error when:
Using a custom ModelView, both Actions (GET and POST) were passing the ModelView that contained two objects:
And the POST also accepting the same model view:
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:
Hope this can help somebody (I spent almost half day to find this out!).
对我来说也一样。
我的问题出现是因为我忘记了我的基模型类已经具有视图中定义的名称的属性。
...和控制器处理模型:
没什么特别的,对吧?但后来我定义了视图……
这会导致 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.
... and controller processing model :
Nothing special, right? But then i define the view ...
... which causes "Parameterless constructor" error on POST request.
Hope that helps.
我遇到了类似的问题,基本上要点是操作方法中有一些参数不是由模型绑定过程提供的(换句话说,这些字段不是由提交页面提交的)。
即使提供了除一个之外的所有参数,并且即使缺少一个可为 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.
我也遇到了这个问题,并认为我会分享,因为我在上面找不到我的问题。
这是我的代码
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});
由于没有无参数公共构造函数,我遇到了同样的异常,
代码如下:
更改为
问题已解决。
I got same exception due to there was no parameterless public contructor
Code was like this:
changed to
problem resolved to me.
所有答案都说创建一个无参数构造函数,如果您不希望任何其他开发人员使用它而只使用模型绑定器,那么这并不理想。
如果另一个开发人员尝试使用公共构造函数上方的属性
[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.我收到这个错误。我在构造函数中使用接口,而我的依赖解析器无法解析,当我注册它时,错误就消失了。
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.
我遇到了同样的问题...
如果您使用接口来解耦与 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 >().
虽然这对某些人来说可能是显而易见的,但对我来说,这个错误的罪魁祸首是我的 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.由于缺少依赖项注入器/解析器容器和/或缺少绑定,可能会出现此类型错误
UnityMConfig.cs
UnityMvcActivator.cs
This type error may come up due to missing dependency injector/resolver container and/or missing the bindings
UnityMConfig.cs
UnityMvcActivator.cs
我遇到了同样的问题,但后来发现添加任何新接口和相应的类都需要将其注册在可初始化模块下以进行依赖项注入。就我而言,它的内部代码如下:
}
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:
}
就我而言,我的类具有
[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]
我向 DOMAIN 文件夹内的模型添加了一个无参数构造函数,问题得到了解决。
I added a parameterless constructor to the model inside of DOMAIN Folder, and the problem is solved.
当尝试在 DbContext 类上添加迁移时,我遇到了同样的问题。
首先,我收到错误:无法创建“ContextDb”类型的对象。有关设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink /?linkid=851728
这让我添加了接口 IDesignTimeDbContextFactory 并实现了它的功能:
此时再次尝试 Add-Migration 时出现错误 Noparameterlessconstructor Defined for type 'LibraryContext.ContextDb' 。这是由于在 CreateDbContext() 中创建了 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:
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:
当我添加一种新的方法来实例化类时,这个错误就开始出现了。
示例:
当我进行此更改(添加无参数构造函数)时,错误已解决。我相信编译器默认创建一个无参数构造函数,但如果您添加自己的构造函数,则必须显式创建它。
This error started for me when I added a new way to instantiate a class.
Example:
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.
我已在表单中添加了一个
DropDownList
,但就我而言,它没有(也无意)与表单一起提交,因为它位于标签:
由于 Model 包含仅用于显示的字段,这也会导致
Noparameterlessconstructordefineforthisobject
错误,因为该字段根本没有提交。在这种情况下,我通过添加排除绑定来修复它:
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: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:
这发生在我身上,这个页面上的结果是一个很好的资源,引导我走向很多方向,但我想添加另一种可能性:
正如其他回复中所述,创建带参数的构造函数会删除隐式无参数构造函数,因此您必须明确键入它。
我的问题是具有默认参数的构造函数也触发了此异常。
给出错误:
有效:
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:
Works:
最有可能的是,您的控制器中可能有参数化构造函数,并且您使用的任何依赖项解析器都无法正确解析依赖项。您需要在编写依赖解析器方法的位置放置断点,然后您将在内部异常中得到确切的错误。
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.
我也有同样的问题。
刚刚从 Post Action 方法参数中删除了
HttpFileCollectionBase files
并在方法主体中添加类似
HttpFileCollectionBase files = Request.Files;
的内容。I had the same problem.
Just Removed
HttpFileCollectionBase files
from Post Action method argumentand added like
HttpFileCollectionBase files = Request.Files;
in method body.所以我之前在进行 ajax 调用时也收到过该消息。所以它基本上要求的是控制器调用的模型类中的构造函数,没有任何参数。
这是一个例子
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