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 프로젝트에 추가했습니다. [참고 : 이것은 붉은 청어 일 수 있습니다.]
그 후에는 더 이상 프로젝트를로드 할 수 없습니다. 위의 오류로 인해 차가워졌습니다.
내 질문은 "내 코드를 수정하도록 도와 줄 수 있습니까?" 가 아닙니다 .
대신 더 일반적으로 알고 싶습니다.
- 이 문제를 어떻게 해결해야합니까?
- 무엇을 찾아야합니까?
- 근본 원인은 무엇입니까?
지금보다 더 깊이있는 라우팅과 컨트롤러를 이해해야 할 것 같습니다.
방금 비슷한 문제가있었습니다. 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
{
}
}
이것은 매개 변수가없는 생성자가 없으므로 모델에서 SelectList를 사용하는 경우에도 발생할 수 있습니다 .
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; }
}
파라미터가없는 컨트롤러에 해당하는 조치가 필요합니다.
가지고있는 컨트롤러 / 액션 조합은 다음과 같습니다.
public ActionResult Action(int parameter)
{
}
하지만 당신은 필요합니다
public ActionResult Action()
{
}
또한 Phil Haack의 Route Debugger 를 확인하여 경로 문제를 해결하십시오.
기본적으로 MVC 컨트롤러에는 매개 변수가없는 기본 생성자가 필요합니다. 가장 간단한 방법은 매개 변수가있는 생성자를 호출하는 기본 생성자를 만드는 것입니다.
public MyController() : this(new Helper()) {
}
public MyController(IHelper helper) {
this.helper = helper;
}
그러나 자신의 롤링하여이 기능을 재정의 할 수 있습니다 ControllerFactory
. 이 방법으로 MVC MyController
에게 인스턴스를 만들 때 인스턴스를 제공 한다고 알릴 수 있습니다 Helper
.
이를 통해 MVC와 함께 Dependency Injection 프레임 워크를 사용하고 실제로 모든 것을 분리 할 수 있습니다. 이것의 좋은 예는 StructureMap 웹 사이트 에서 끝났습니다 . 전체 퀵 스타트가 양호하고 "자동 배선"에서 MVC를 바닥으로 향하게됩니다.
이 오류는 IoC 컨테이너를 사용할 때와 같이 IDependencyResolver를 사용할 때도 발생 하며 종속성 해결 프로그램이 널을 리턴합니다. 이 경우 ASP.NET MVC 3은 기본적으로 DefaultControllerActivator를 사용하여 개체를 만듭니다. 작성중인 오브젝트에 인수없는 공용 생성자가없는 경우 제공된 종속성 분석기가 널을 리턴 할 때마다 예외가 발생합니다.
이러한 스택 추적 중 하나가 있습니다.
[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
MVC 프레임 워크의 여러 곳에서이 예외가 발생할 수 있습니다 (예 : 컨트롤러를 만들 수 없거나 해당 컨트롤러에 모델을 만들 수 없음).
이 문제를 진단하는 가장 쉬운 방법은 자신의 코드로 가능한 한 예외에 가깝게 MVC를 재정의하는 것입니다. 그런 다음이 예외가 발생하면 Visual Studio에서 코드가 중단되고 스택 추적에서 문제를 일으키는 Type을 읽을 수 있습니다.
이것은이 문제에 접근하는 끔찍한 방법처럼 보이지만 매우 빠르고 일관성이 있습니다.
예를 들어, 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의 다른 확장 점 (예 : 컨트롤러 구성)에 대해 유사한 코드를 작성할 수 있습니다.
같은 오류가 발생했습니다. 제 경우 범인은 public 또는 private이 아닌 생성자 였습니다 .
이 객체에 대해 매개 변수가없는 생성자가 정의되어 있지 않습니다.
예외 정보 : System.MissingMethodException :이 개체에 대해 매개 변수가없는 생성자가 정의되어 있지 않습니다.
재현 코드 : 생성자가 공개하기 전에 확인하십시오.
public class Chuchi()
{
Chuchi() // The problem is this line. Public is missing
{
// initialization
name="Tom Hanks";
}
public string name
{
get;
set;
}
}
http://tekpub.com/conferences/mvcconf의 첫 번째 비디오
47:10 분 후 오류가 표시되고 기본 ControllerFactory를 대체하는 방법을 보여줍니다. 즉, 구조 맵 컨트롤러 팩토리를 작성합니다.
기본적으로 의존성 주입을 구현하려고합니까?
문제는 인터페이스 의존성입니다.
다음과 같은 경우에 같은 오류가 발생했습니다.
사용자 정의 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)
{...}
문제는 View가 ModelView (제품 및 카테고리 정보 목록이 필요함)를 수신했지만 제출 후 Product 객체 만 반환했지만 POST Add는 ProductModelView를 예상했지만 NULL을 전달했지만 ProductModelView 만 생성자에는 두 개의 매개 변수가 필요했습니다 ( Product, Root 카테고리),이 NULL 케이스에 대한 매개 변수가없는 다른 생성자를 찾으려고하면 "no parameterles ..."로 실패합니다.
따라서 다음과 같이 POST 추가를 수정하여 문제점을 정정하십시오.
[HttpPost]
[ValidateInput(false)]
public ActionResult Add(Product product)
{...}
이것이 누군가를 도울 수 있기를 바랍니다 (거의 반나절을 보냈습니다!).
저도 마찬가지입니다. 내 기본 모델 클래스에 이미 뷰에 정의 된 이름의 속성이 있다는 것을 잊었 기 때문에 문제가 발생했습니다 .
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 요청시 "매개 변수없는 생성자"오류가 발생합니다.
희망이 도움이됩니다.
비슷한 문제가 있었으며 기본적으로 모델 바인딩 프로세스에서 제공하지 않은 액션 메소드에 몇 가지 인수가 있습니다 (즉,이 필드는 제출 페이지에서 제출하지 않았습니다).
하나를 제외한 모든 인수가 제공되고 누락 된 인수가 널 입력 가능 유형 인 경우에도이 문제가 발생합니다.
문제는 오타의 결과 일 수도 있는데, 인수의 이름과 양식 필드의 이름이 동일하지 않습니다.
해결책은 1) 이름이 일치하는지 확인 2) 인수에 대한 기본값을 제공하거나 3)이 인수없이 다른 조치 방법을 제공하는 것입니다.
나는이 문제도 있었고 위의 문제를 찾을 수 없으므로 공유 할 것이라고 생각했습니다.
이것은 내 코드였다
return RedirectToAction("Overview", model.Id);
이 ActionResult 호출 :
public ActionResult Overview(int id)
나는 그것을 전달하는 가치가 Overview의 id 매개 변수라는 것을 알기에 충분할 것이라고 생각했지만 그렇지 않습니다. 이것은 그것을 고쳤다 :
return RedirectToAction("Overview", new {id = model.Id});
매개 변수가없는 공개 컨스트럭터가 없기 때문에 동일한 예외가 발생했습니다.
코드는 다음과 같습니다
public class HomeController : Controller
{
private HomeController()
{
_repo = new Repository();
}
로 변경
public class HomeController : Controller
{
public HomeController()
{
_repo = new Repository();
}
문제가 해결되었습니다.
나는 같은 문제가 있었다 ...
인터페이스를 사용하여 나와 같은 DbContext에 대한 연결을 분리하는 경우 structuremap.mvc (3 또는 4-너지 트 패키지 )를 사용하여 컨트롤러 클래스에서 구문을 사용할 수 있습니다. 그러면 DependencyResolution 폴더가 제공됩니다. 주석 처리 된 줄을 For <InterfaceClass> ()로 변경하고 <DbContextClass> ()를 사용하십시오.
이것이 어떤 사람들에게는 명백 할 수도 있지만, 저 에게이 오류의 원인은 MVC 메소드가 type 속성을 포함하는 모델에 바인딩하고 있다는 것 Tuple<>
입니다. Tuple<>
매개 변수가없는 생성자가 없습니다.
모든 대답은 매개 변수가 적은 생성자를 생성한다고 말하지만 다른 개발자가 모델 바인더 만 사용하지 않으려는 경우에는 적합하지 않습니다.
[Obsolete("For model binding only", true)]
다른 생성자가 이것을 사용하려고하면 공용 생성자 위 의 속성 에서 컴파일러 오류가 발생합니다. 이것을 찾기 위해 나이가 들었습니다. 누군가에게 도움이되기를 바랍니다.
이 오류가 발생했습니다. 생성자에서 인터페이스를 사용하고 있었고 의존성 해결 프로그램을 확인할 수 없었습니다. 등록하면 오류가 사라졌습니다.
내 경우에는 내 클래스에 [Serializable]
특성이 있습니다.
클래스가 다음과 같은 경우 매개 변수를 사용하지 않는 생성자가 있어야합니다. [Serializable]
이 오류는 클래스를 인스턴스화하는 새로운 방법을 추가했을 때 시작되었습니다.
예:
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;
}
}
DropDownList
내 양식 에 a 를 추가 했지만 내 경우에는 <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)
이것은 나에게 일어 났 으며이 페이지의 결과는 많은 방향으로 이끌 수있는 좋은 자료 였지만 다른 가능성을 추가하고 싶습니다.
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){}
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.
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)
{
}
}
}
I had the same problem.
Just Removed HttpFileCollectionBase files
from Post Action method argument and added like HttpFileCollectionBase files = Request.Files;
in method body.
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
}
'IT' 카테고리의 다른 글
알파벳순으로 목록을 정렬하려면 어떻게해야합니까? (0) | 2020.05.29 |
---|---|
큰 Ө 표기법은 정확히 무엇을 의미합니까? (0) | 2020.05.29 |
백업을 복원 할 때 모든 활성 연결을 해제하려면 어떻게합니까? (0) | 2020.05.29 |
날짜 시간 소인을 작성하고 ISO 8601, RFC 3339, UTC 시간대로 형식을 지정하는 방법은 무엇입니까? (0) | 2020.05.29 |
컴퓨터에서 .NET Framework 버전을 반환하는 PowerShell 스크립트? (0) | 2020.05.29 |