【问题标题】:How to deal with "The message cannot be deserialized into MessageContract type" in .NET如何在.NET中处理“消息无法反序列化为MessageContract类型”
【发布时间】:2021-09-29 16:27:03
【问题描述】:

通过单击“创建”按钮发送在数据库中添加新会员用户的请求后,我收到“消息无法反序列化为 MessageContract 类型 FXM.Ordering.WS.Contract.BoCreateAffiliateRequest 因为它没有默认(无参数)构造函数。”

screenshot of UI and error message

我的控制器:

 [HttpPost]
        public JsonResult CreateAffiliate(NewAffiliateViewModel newAffiliateViewModel)
        {
            try
            {
                var res = BackOfficeServices.BoAddAffiliateUser(newAffiliateViewModel);
                //SystemServices.ResendEmail(userId);
                return Json("success");

                //return Json(result, JsonRequestBehavior.DenyGet);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

我的 ajax 请求


@*<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>*@
<script type="text/javascript">
    // document.ready function
    $(function () {
        refreshGroups();
        refreshEmployees();
        // selector has to be . for a class name and # for an ID
        $('#create-affiliate-button').click(function (e) {
            //e.preventDefault(); // prevent form from reloading page
            console.log("blahblahblah");
            //alert("hiii");

            var b = $("form").serialize();
            //var a = $("form").serializeArray();
            console.log("formvalues", b);

            $.ajax({
                @*url: "@Url.Action("CreateAffiliate", "AjaxUI")",*@
                url: "/en/AjaxUI/CreateAffiliate",
                type: "POST",
            //dataType: "json",
            data: b,
               
            

                //error: function (jqXHR, exception) {
                //    failMessage();
                //}
            });
        });
    });



    function refreshGroups() {
        var pltf = "MT4_LIVE";
        var out = $('#MT4Group');
        if (pltf != null && pltf !== "") {
            $.ajax({
                url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
                data: {
                    platform: pltf, currency: "", withId : true
                },
                type: 'GET',
                beforeSend: function () {
                    $('#tpLoader').show();
                },
                complete: function () {
                    $('#tpLoader').hide();
                },
                success: function (data) {
                    populateDropDown(out, data);
                    //$('#recomandedGroup').show();
                }
            });
        } else {
            out.empty();
            out.append($('<option></option>').val('').html(window.defaultSelection));
        }
    }

    //function urlResult() {
    //    return "/" + window.langlang + "/AjaxUI/CreateAffiliate";
    //}


    function refreshEmployees() {
        //debugger;
        //var pltf = "MT4_LIVE";
        var out = $('#Employee');
        //if (pltf != null && pltf !== "") {
            $.ajax({
                url: "/en/BOEmployeeAjax/GetEmployeesExcept",
                data: {
                    emplId : 0
                    //platform: pltf, currency: "", withId: true
                },
                type: 'POST',
                beforeSend: function () {
                    $('#tpLoader').show();
                },
                complete: function () {
                    $('#tpLoader').hide();
                },
                success: function (data) {
                    //populateDropDown(out, data);
                    //$('#recomandedGroup').show();
                    //debugger;
                    for(var value of data)
                    out.append($('<option>' + value.text + '</option>').val(value.id))

                }
            });

我的视图模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FXM.BO.ViewModels
{
    public class NewAffiliateViewModel
    {
        public NewAffiliateViewModel()
        {
        }

        public int Id { get; set; }

        public string AffiliateName { get; set; }

        public string Email { get; set; }


        public int Employee { get; set; }


        public int MT4Group { get; set; }
    }
}

到目前为止,我尝试的是在谷歌上搜索问题并尝试添加无参数控制器,但我不确定它是否正确完成,因为它没有解决问题。我错过了什么?

我的 Startup.cs 代码:

using Autofac;
using Autofac.Integration.Wcf;
using FXM.Ordering.WS.Core.DependencyManagement;
using FXM.Ordering.WS.Reporting;
using FXM.Ordering.WS.Utils;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(FXM.Ordering.WS.Startup))]

namespace FXM.Ordering.WS
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {                                               
            IContainer container = AutofacContainerBuilder.BuildContainer();            
            AutofacHostFactory.Container = container;
            app.UseAutofacMiddleware(container);
            log4net.Config.XmlConfigurator.Configure();
        }
    }
} 

我不确定如何添加您提供的代码。

【问题讨论】:

  • 错误提示 BoCreateAffiliateReques does not have a default (parameterless) constructor。那个班在哪里?它必须有一个默认构造函数
  • 删除catch (Exception e) { throw e; }。它只是截断异常的堆栈跟踪。如果您想为断点设置占位符,请使用 catch { throw;}。看起来您正在尝试使用缺少构造函数的类来调用 SOAP 服务。异常的调用堆栈会显示哪些方法调用导致了异常,但现在只显示throw ex 被调用的位置
  • 另一方面,当出现问题时,WCF 服务器 通常会抛出FaultException。你检查过网络服务的日志吗?和。 .... 等等 ...... 2901 线的控制器??????这需要一些认真的重构。

标签: c# .net asp.net-mvc deserialization


【解决方案1】:

我假设您使用的是注射容器。如果是这样,那么它可能没有注册。在 Startup.cs 中获取 IServiceCollection:

services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
            .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
            .Where(t => typeof(IController).IsAssignableFrom(t)
            || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

这会将所有控制器添加到容器中。检查您的配置并确保它已注册

【讨论】:

  • 我将我的 Startup.cs 代码上传为 EDIT-1。我不确定如何添加您提供的代码。我也不知道如何检查我的配置以确保它已注册。
  • 报错是类构造函数,而不是服务注册。
猜你喜欢
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2017-08-07
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2017-12-01
相关资源
最近更新 更多