ASP.NET MVC: No parameterless constructor defined

2019-01-01 08:37发布

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.

25条回答
浪荡孟婆
2楼-- · 2019-01-01 09:24

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

查看更多
回忆,回不去的记忆
3楼-- · 2019-01-01 09:24

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

查看更多
千与千寻千般痛.
4楼-- · 2019-01-01 09:25

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.

查看更多
素衣白纱
5楼-- · 2019-01-01 09:26

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
查看更多
美炸的是我
6楼-- · 2019-01-01 09:28

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.

查看更多
何处买醉
7楼-- · 2019-01-01 09:28

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

查看更多
登录 后发表回答