【问题标题】:Internal exception has occured: Type '<>f__AnonymousType2`6[...]' cannot be serialized发生内部异常:类型 '<>f__AnonymousType2`6[...]' 无法序列化
【发布时间】:2019-12-02 10:03:03
【问题描述】:

我已经在 ASP.net 中编写了一个端点(它应该返回一个不错的 JSON)并且以下错误让我感到困惑,因为通过我的 Swagger 界面,一切正常,但是如果我直接在浏览器中使用 @987654322 调用端点@,我收到:

发生内部异常:无法序列化类型“f__AnonymousType2`6[System.String,System.DateTime]”。考虑使用 DataContractAttribute 属性对其进行标记,并使用 DataMemberAttribute 属性标记您想要序列化的所有成员。如果类型是集合,请考虑使用 CollectionDataContractAttribute 对其进行标记。 有关其他支持的类型,请参阅 Microsoft .NET Framework 文档。

这看起来很奇怪,因为我认为我确实实现了一个无参数(默认)构造函数。我的代码如下

using AutoMapper;
using myProject.API.Filters;
using myProject.API.Models;
using myProject.Entity.DAL;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace myProject.API.Controllers
{
    [UserAuthenticationFilter]
    public class AutoUploadController : BaseController
    {
        public AutoUploadController() {
            System.Diagnostics.Debug.WriteLine("Parameterless default constructor only for serialization");
        }

        // GET: api/AutoUpload
        [ResponseType(typeof(IEnumerable<FilesDetailsDto>))]
        public IHttpActionResult GetAutoUpload(string OptionString = "status")
        {
            if (OptionString == "status")
            {
                var rootLocation = ConfigurationManager.AppSettings["ROOT-FOLDER-LOCATION"];
                string[] entries = Directory.GetFiles(rootLocation, "*.csv", SearchOption.AllDirectories);
                var convList = entries.Select(x => new
                {
                    FullPath = x,
                    LastModifed = System.IO.File.GetLastWriteTime(x)
                });

                return Ok(convList.AsEnumerable());
            } // end IF-clause for optional parameter
            else
            {
                return NotFound();
            }
        }
    }
}

上述代码使用以下数据传输对象(DTO)定义:

using System;

namespace myProject.API.Models
{
    public class FilesDetailsDto
    {
        public string FileName { get; set; }
        public DateTime LastModifiedOnFilesystem { get; set; }
    }
}

参考文献

【问题讨论】:

    标签: c# asp.net rest


    【解决方案1】:

    您返回的是匿名类型的集合,而不是定义为属性的实际类型,这可能是导致此错误的罪魁祸首。

    在此处使用Select 时,您可以尝试更加明确:

    var convList = entries.Select(x => new FilesDetailsDto()
                {
                    FullPath = x,
                    LastModifiedOnFilesystem = System.IO.File.GetLastWriteTime(x)
                });
    

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      相关资源
      最近更新 更多