ASP.NET Core格式化器:数据序列化

ASP.NET Core格式化器:数据序列化

【免费下载链接】aspnetcore dotnet/aspnetcore: 是一个 ASP.NET Core 应用程序开发框架的官方 GitHub 仓库,它包含了 ASP.NET Core 的核心源代码和技术文档。适合用于 ASP.NET Core 应用程序开发,特别是对于那些需要深入了解 ASP.NET Core 框架实现和技术的场景。特点是 ASP.NET Core 官方仓库、核心源代码、技术文档。 【免费下载链接】aspnetcore 项目地址: https://gitcode.com/GitHub_Trending/as/aspnetcore

引言

在现代Web开发中,数据序列化(Serialization)是API通信的核心环节。ASP.NET Core提供了强大的格式化器(Formatter)系统,能够自动处理HTTP请求和响应中的数据转换。本文将深入探讨ASP.NET Core格式化器的工作原理、配置方式以及最佳实践,帮助开发者构建高效、灵活的Web API。

格式化器体系架构

核心接口与类

ASP.NET Core的格式化器系统基于以下核心接口构建:

public interface IInputFormatter
{
    bool CanRead(InputFormatterContext context);
    Task<InputFormatterResult> ReadAsync(InputFormatterContext context);
}

public interface IOutputFormatter
{
    bool CanWriteResult(OutputFormatterCanWriteContext context);
    Task WriteAsync(OutputFormatterWriteContext context);
}

格式化器工作流程

mermaid

内置格式化器详解

System.Text.Json格式化器

ASP.NET Core默认使用System.Text.Json作为JSON序列化引擎,提供高性能的JSON处理能力。

输入格式化器配置
public class SystemTextJsonInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy
{
    public SystemTextJsonInputFormatter(
        JsonOptions jsonOptions, 
        ILogger<SystemTextJsonInputFormatter> logger)
    {
        SupportedEncodings.Add(UTF8EncodingWithoutBOM);
        SupportedEncodings.Add(UTF16EncodingLittleEndian);
        
        SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson);
        SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson);
        SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax);
    }
}
输出格式化器实现
public class SystemTextJsonOutputFormatter : TextOutputFormatter
{
    private readonly JsonSerializerOptions _jsonSerializerOptions;

    public SystemTextJsonOutputFormatter(JsonSerializerOptions jsonSerializerOptions)
    {
        _jsonSerializerOptions = jsonSerializerOptions;
        
        SupportedEncodings.Add(UTF8EncodingWithoutBOM);
        SupportedEncodings.Add(UTF16EncodingLittleEndian);
        
        SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson);
        SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson);
        SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax);
    }

    public override async Task WriteResponseBodyAsync(
        OutputFormatterWriteContext context, 
        Encoding selectedEncoding)
    {
        var response = context.HttpContext.Response;
        var objectType = context.Object?.GetType() ?? typeof(object);
        
        await JsonSerializer.SerializeAsync(
            response.Body, 
            context.Object, 
            objectType, 
            _jsonSerializerOptions);
    }
}

XML格式化器支持

ASP.NET Core同样提供XML序列化支持,包括XmlSerializerDataContractSerializer两种实现。

// XML序列化器配置
services.AddMvc().AddXmlSerializerFormatters();
// 或者使用DataContract序列化器
services.AddMvc().AddXmlDataContractSerializerFormatters();

配置与自定义

JsonOptions配置

services.Configure<JsonOptions>(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    options.JsonSerializerOptions.WriteIndented = true;
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

自定义格式化器实现

创建自定义输入格式化器
public class CustomCsvInputFormatter : TextInputFormatter
{
    public CustomCsvInputFormatter()
    {
        SupportedMediaTypes.Add("text/csv");
        SupportedEncodings.Add(Encoding.UTF8);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(
        InputFormatterContext context, Encoding encoding)
    {
        using var reader = new StreamReader(context.HttpContext.Request.Body, encoding);
        var content = await reader.ReadToEndAsync();
        
        // 自定义CSV解析逻辑
        var result = ParseCsv(content, context.ModelType);
        return await InputFormatterResult.SuccessAsync(result);
    }
    
    private object ParseCsv(string csvContent, Type targetType)
    {
        // 实现CSV到对象的转换逻辑
        return Activator.CreateInstance(targetType);
    }
}
创建自定义输出格式化器
public class CustomCsvOutputFormatter : TextOutputFormatter
{
    public CustomCsvOutputFormatter()
    {
        SupportedMediaTypes.Add("text/csv");
        SupportedEncodings.Add(Encoding.UTF8);
    }

    public override async Task WriteResponseBodyAsync(
        OutputFormatterWriteContext context, Encoding encoding)
    {
        var response = context.HttpContext.Response;
        var csvContent = ConvertToCsv(context.Object);
        
        await response.WriteAsync(csvContent, encoding);
    }
    
    private string ConvertToCsv(object value)
    {
        // 实现对象到CSV的转换逻辑
        return "csv,content,here";
    }
}

内容协商机制

媒体类型协商

ASP.NET Core使用内容协商(Content Negotiation)机制自动选择最合适的格式化器:

// 客户端通过Accept头指定期望的响应格式
// Accept: application/json, application/xml;q=0.9

格式化器选择优先级

选择因素优先级说明
Media Type根据Content-Type/Accept头匹配
Encoding字符编码匹配
Formatter顺序MVC选项中的注册顺序

性能优化策略

序列化性能对比

mermaid

最佳实践建议

  1. 使用System.Text.Json作为默认选择

    • 更高的性能
    • 更低的内存分配
    • 更好的安全性
  2. 合理配置JsonSerializerOptions

    services.Configure<JsonOptions>(options =>
    {
        // 启用源码生成以提高性能
        options.JsonSerializerOptions.TypeInfoResolver = 
            MyJsonContext.Default;
    
        // 配置合理的默认值
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });
    
  3. 避免频繁创建JsonSerializerOptions实例

    • 重用配置实例
    • 使用依赖注入管理配置

高级应用场景

多态序列化支持

[JsonDerivedType(typeof(Employee), typeDiscriminator: "employee")]
[JsonDerivedType(typeof(Manager), typeDiscriminator: "manager")]
public abstract class Person
{
    public string Name { get; set; }
}

public class Employee : Person
{
    public string Department { get; set; }
}

public class Manager : Person
{
    public int TeamSize { get; set; }
}

流式序列化处理

对于大型数据集,可以使用流式序列化减少内存压力:

public async IAsyncEnumerable<DataItem> GetLargeData()
{
    for (int i = 0; i < 1000000; i++)
    {
        yield return new DataItem { Id = i, Value = $"Item {i}" };
        await Task.Delay(1); // 模拟异步操作
    }
}

错误处理与调试

异常处理策略

services.Configure<JsonOptions>(options =>
{
    options.JsonSerializerOptions.AllowTrailingCommas = true;
    options.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
    options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
});

调试技巧

  1. 启用详细错误信息

    services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = false;
        options.InvalidModelStateResponseFactory = context =>
        {
            var problemDetails = new ValidationProblemDetails(context.ModelState);
            return new BadRequestObjectResult(problemDetails);
        };
    });
    
  2. 自定义错误响应格式

    public class CustomProblemDetails : ProblemDetails
    {
        public string TraceId { get; set; }
        public Dictionary<string, string[]> Errors { get; set; }
    }
    

总结

ASP.NET Core的格式化器系统提供了强大而灵活的数据序列化能力。通过合理配置和使用内置的System.Text.Json格式化器,开发者可以构建高性能的Web API。对于特殊需求,可以通过实现自定义格式化器来扩展功能。

关键要点回顾

  • 默认使用System.Text.Json:性能更优,内存占用更少
  • 支持内容协商:自动根据客户端需求选择合适格式
  • 易于扩展:可以创建自定义格式化器处理特殊格式
  • 配置灵活:通过JsonOptions精细控制序列化行为

通过掌握ASP.NET Core格式化器的使用技巧,开发者可以构建出既高效又灵活的Web API服务,满足各种复杂的业务场景需求。

【免费下载链接】aspnetcore dotnet/aspnetcore: 是一个 ASP.NET Core 应用程序开发框架的官方 GitHub 仓库,它包含了 ASP.NET Core 的核心源代码和技术文档。适合用于 ASP.NET Core 应用程序开发,特别是对于那些需要深入了解 ASP.NET Core 框架实现和技术的场景。特点是 ASP.NET Core 官方仓库、核心源代码、技术文档。 【免费下载链接】aspnetcore 项目地址: https://gitcode.com/GitHub_Trending/as/aspnetcore

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值