asp.net-mvc ASP.NET MVC:没有为此对象定义无参数构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1355464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC: No parameterless constructor defined for this object
提问by Jim G.
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.]
我正在关注 Steven Sanderson 的“ Pro ASP.NET MVC Framework”一书。在第132页,按照作者的推荐,我下载了ASP.NET MVC Futures程序集,并将其添加到我的MVC项目中。[注意:这可能是一个红鲱鱼。]
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.
看起来我应该比现在更深入地了解路由和控制器。
回答by SandRock
I just had a similar problem. The same exception occurs when a Modelhas no parameterless constructor.
我刚刚遇到了类似的问题。当 aModel没有无参数构造函数时会发生相同的异常。
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)
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
{
}
}
回答by Chris S
This can also be caused if your Model is using a SelectList, as this has no parameterless constructor:
如果您的模型使用 SelectList,这也可能导致,因为它没有无参数构造函数:
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:
如果这是原因,您将需要重构您的模型以采用不同的方式。因此,使用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(..)
}
Or you can use the @Mark and @krilovich approach, just need replace SelectList to IEnumerable, it's works with MultiSelectList too.
或者您可以使用@Mark 和@krilovich 方法,只需要将SelectList 替换为IEnumerable,它也适用于MultiSelectList。
public class MyViewModel
{
public Contact SelectedContact { get;set; }
public IEnumerable<SelectListItem> Contacts { get;set; }
}
回答by Martin
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 Debuggerto troubleshoot routes.
此外,请查看 Phil Haack 的Route Debugger以对路由进行故障排除。
回答by swilliams
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:
默认情况下,MVC 控制器需要一个没有参数的默认构造函数。最简单的方法是创建一个默认构造函数来调用带有参数的构造函数:
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 MyControllergive it an instance of Helper.
但是,您可以通过滚动自己的ControllerFactory. 通过这种方式,您可以告诉 MVC,当您创建一个时,MyController给它一个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".
这允许您在 MVC 中使用依赖注入框架,并真正解耦一切。一个很好的例子在StructureMap 网站上。整个快速入门很好,他在“自动布线”的底部详细介绍了 MVC。
回答by Kaleb Pederson
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.
使用IDependencyResolver时也会发生此错误,例如使用 IoC 容器时,并且依赖项解析器返回 null。在这种情况下,ASP.NET MVC 3 默认使用 DefaultControllerActivator 创建对象。如果正在创建的对象没有公共无参数构造函数,则只要提供的依赖项解析器返回 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
回答by Josh Mouch
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).
您可以在 MVC 框架中的许多不同位置获得此异常(例如,它无法创建控制器,或者无法创建模型来提供该控制器)。
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.
我发现诊断此问题的唯一简单方法是使用您自己的代码覆盖尽可能接近异常的 MVC。然后,当发生此异常时,您的代码将在 Visual Studio 中中断,您可以从堆栈跟踪中读取导致问题的类型。
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:
例如,如果此错误发生在 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);
}
}
And update your Global.asax.cs:
并更新您的 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.
现在,下次您遇到该异常时,Visual Studio 将停止在您的 MyDefaultModelBinder 类中,您可以检查“modelType”属性以查看导致问题的类型。
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).
上面的示例仅适用于在模型绑定期间获得“没有为此对象定义无参数构造函数”异常的情况。但是可以为 MVC 中的其他扩展点编写类似的代码(例如控制器构造)。
回答by Hammad Khan
I got the same error, the culprit in my case was the constructor which was neither public nor private.
我遇到了同样的错误,在我的案例中罪魁祸首是既不是 public 也不是 private的构造函数。
No parameterless constructor defined for this object.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
没有为此对象定义无参数构造函数。
异常详细信息:System.MissingMethodException:没有为此对象定义无参数构造函数。
Repro code: Make sure the constructor has public before it.
重现代码:确保构造函数之前有 public。
public class Chuchi()
{
Chuchi() // The problem is this line. Public is missing
{
// initialization
name="Tom Hanks";
}
public string name
{
get;
set;
}
}
回答by Dan B
First video on http://tekpub.com/conferences/mvcconf
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.
47:10 分钟显示错误并显示如何覆盖默认 ControllerFactory。即创建结构图控制器工厂。
Basically, you are probably trying to implement dependency injection??
基本上,您可能正在尝试实现依赖注入??
The problem is that is the interface dependency.
问题是接口依赖。
回答by Nestor
I got the same error when:
我在以下情况下遇到了同样的错误:
Using a custom ModelView, both Actions (GET and POST) were passing the ModelView that contained two objects:
使用自定义 ModelView,两个操作(GET 和 POST)都传递包含两个对象的 ModelView:
public ActionResult Add(int? categoryID)
{
...
ProductViewModel productViewModel = new ProductViewModel(
product,
rootCategories
);
return View(productViewModel);
}
And the POST also accepting the same model view:
并且 POST 也接受相同的模型视图:
[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..."
问题是 View 收到了 ModelView(需要产品和类别信息列表),但提交后只返回 Product 对象,但由于 POST Add 期望 ProductModelView,它传递了一个 NULL 但随后 ProductModelView 仅构造函数需要两个参数( Product, RootCategories),然后它尝试为这个 NULL 情况找到另一个没有参数的构造函数,然后失败并显示“没有参数......”
So, fixing the POST Add as follows correct the problem:
因此,修复 POST 添加如下更正问题:
[HttpPost]
[ValidateInput(false)]
public ActionResult Add(Product product)
{...}
Hope this can help somebody (I spent almost half day to find this out!).
希望这可以帮助某人(我花了将近半天的时间找到了这个!)。
回答by Anonymous
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.
...这会导致 POST 请求出现“无参数构造函数”错误。
Hope that helps.
希望有帮助。

