微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ModelBinding引发错误没有为此对象定义无参数构造函数

如何解决ModelBinding引发错误没有为此对象定义无参数构造函数

我有一个如下所示的API端点,

public ActionResult GetData([FromBody] Employee emp)
{
  
}

我有一个像下面这样的课程:

public class Employee : Department
{
  public string EmpName {get; set;}
  public string EmpDetails {get; set;}

}

public class Department
{
    public string DeptName {get; set;}
    public TimeZoneInfo ClientTimeZoneInfo { get; set; }
}

当我通过下面的对象时,它的工作正常且端点已命中

{
  "EmpName" : "Demo","EmpDetails" : "Test","DeptName" : "Cargo"
}

但是当我像下面那样传递我的objext时,抛出错误并且端点没有命中

{
  "EmpName" : "Demo","DeptName" : "Cargo",}

当我单击UI上的按钮时,它将调用我的javaScript方法ReplyMesaage(Employee)和obj == Employee对象

  replyMessage(obj) {
        let that = this;
        var token = $('input[name="__RequestVerificationToken"]').val();
        // call to get the reply message partial view markup
        $.ajax({
            type: "POST",url: "/Messages/GetData",data: { __RequestVerificationToken: token,model: obj },success: function (data) {
                $(window).scrollTop(0);
                var panelbar = $("#Dump").data("kendoPanelBar");
                panelbar.insertBefore({
                    text: "",encoded: false,content: data,expanded: true,collapse: function (e) {
                        if (e.item.class.contains('reply'))
                            e.preventDefault();
                    }
                },panelbar.element.children("li:first"));
                var isInternal = $("#test").val();
                var message = $("#subject").val();
                var TypeValue = $("#TypeValue").val();
                that.loadRecipientList(isInternal,message,TypeValue);
            }
        });

例外:
没有为此对象定义无参数构造函数

有人可以帮我解决这个问题吗?

完全例外:

<!DOCTYPE html>
<html>
    <head>
        <title>No parameterless constructor defined for this object.</title>
        <Meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:pointer; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>No parameterless constructor defined for this object.</i> </h2></span>

            <font face="Arial,Helvetica,Geneva,SunSans-Regular,sans-serif ">

            <b> Description: </b>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.

            <br><br>

            <b> Exception Details: </b>System.MissingMethodException: No parameterless constructor defined for this object.<br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code>

An unhandled exception was generated during the execution of the current web request. information regarding the origin and location of the exception can be identified using the exception stack trace below.                      </code>

                  </td>
               </tr>
            </table>

            <br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type,Boolean publicOnly,Boolean noCheck,Boolean&amp; canBeCached,RuntimeMethodHandleInternal&amp; ctor,Boolean&amp; bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,Boolean skipCheckThis,Boolean fillCache,StackCrawlMark&amp; stackMark) +122
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,StackCrawlMark&amp; stackMark) +239
   System.Activator.CreateInstance(Type type,Boolean nonPublic) +85
   System.Activator.CreateInstance(Type type) +12
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext,Type modelType) +197

[MissingMethodException: No parameterless constructor defined for this object. Object type &#39;System.TimeZoneInfo&#39;.]
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext,Type modelType) +233
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext,ModelBindingContext bindingContext) +511
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) +333
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext,PropertyDescriptor propertyDescriptor,IModelBinder propertyBinder) +17
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext,PropertyDescriptor propertyDescriptor) +377
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext,ModelBindingContext bindingContext) +101
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext,Object model) +55
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext,ModelBindingContext bindingContext) +1207
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) +333
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext,ParameterDescriptor parameterDescriptor) +335
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext,ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.&lt;&gt;c__displayClass3_1.&lt;BeginInvokeAction&gt;b__0(AsyncCallback asyncCallback,Object asyncState) +640
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback,Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback,Object state,Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext,String actionName,AsyncCallback callback,Object state) +346
   System.Web.Mvc.&lt;&gt;c.&lt;BeginExecuteCore&gt;b__152_0(AsyncCallback asyncCallback,Object asyncState,ExecuteCoreState innerState) +27
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback,Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback,Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback,Object state) +494
   System.Web.Mvc.&lt;&gt;c.&lt;BeginExecute&gt;b__151_1(AsyncCallback asyncCallback,Object callbackState,Controller controller) +16
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback,Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback,Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext,Object state) +403
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext,Object state) +16
   System.Web.Mvc.&lt;&gt;c.&lt;BeginProcessRequest&gt;b__20_0(AsyncCallback asyncCallback,ProcessRequestState innerState) +54
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback,Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext,Object state) +412
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context,AsyncCallback cb,Object exTradata) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +444
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +118
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously) +163
</pre>                      </code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Version information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4210.0

            </font>

    </body>
</html>
<!-- 
[MissingMethodException]: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type,Boolean& canBeCached,RuntimeMethodHandleInternal& ctor,Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type,Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext,Type modelType)
[MissingMethodException]: No parameterless constructor defined for this object. Object type &#39;System.TimeZoneInfo&#39;.
   at System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext,Type modelType)
   at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
   at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
   at System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext,IModelBinder propertyBinder)
   at System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext,PropertyDescriptor propertyDescriptor)
   at System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext,ModelBindingConte…

解决方法

您有两个主要选择:

  1. 创建包含EmpName,EmpDetails和DepName属性的新类EmpDept 并将您的操作更改为GetData([FromBody] EmpDept empDept)

  2. 只需将您的操作更改为GetData([FromBody]字符串EmpName,字符串EmpDetails,字符串DepName = null),然后在操作主体中使用此参数创建新类

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。