首页 > 解决方案 > 如何在.NET中处理“消息无法反序列化为MessageContract类型”

问题描述

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

UI 和错误消息的屏幕截图

我的控制器:

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

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

标签: c#.netasp.net-mvcdeserialization

解决方案


我假设您使用的是注射容器。如果是这样,那么它可能没有注册。以 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)));

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


推荐阅读