ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Ultimate ASP.NET CORE 6.0 Web API --- 读书笔记(7)

2022-06-16 19:33:10  阅读:188  来源: 互联网

标签:CORE ASP 格式化 读书笔记 buffer true company typeof config


Content Negotiation

本文内容来自书籍: Marinko Spasojevic - Ultimate ASP.NET Core Web API - From Zero To Six-Figure Backend Developer (2nd edition)

内容协商是可以让我们API服务对用户更加的友好和灵活,但是因为这样那样的原因,它的使用没有那么的充分

ASP.NET Core 默认返回JSON格式的结果

7.2 Changing the Default Configuration of Our Project

  1. 修改主项目配置,主要是添加XML序列化器
builder.Services
    .AddControllers(config => {
        config.RespectBrowserAcceptHeader = true;
    })
    .AddXmlDataContractSerializerFormatters()
    .AddApplicationPart(
        typeof(CompanyEmployees.Presentation.AssemblyReference).Assembly);
  1. 我们的DTO是个record,所以在返回的时候,会报错,我们需要对这个类型进行处理

    • 在DTO上添加序列化属性[Serializable]
    • 使用init的属性设置
  2. 修改了DTO之后,AutoMapper也要相应修改

CreateMap<Company, CompanyDto>()
    .ForMember(c => c.FullAddress, 
        opt => opt.MapFrom(x => string.Join(' ', x.Address, x.Country)));

7.4 Restricting Media Types

当客户端给服务端发送一些服务端不知道的返回类型的时候,可以通过设置,返回406 Not Acceptable

builder.Services
    .AddControllers(config => {
        config.RespectBrowserAcceptHeader = true;
        config.ReturnHttpNotAcceptable = true;
    })
    .AddXmlDataContractSerializerFormatters()
    .AddApplicationPart(
        typeof(CompanyEmployees.Presentation.AssemblyReference).Assembly);

这样就可以让客户端一定要遵守服务端所支持的类型

7.5 More About Formatters

如果希望API能够支持非常规的格式化,ASP.NET Core支持自定义格式化器

有如下几种方法

  • 输出格式化器:继承TextOutputFormatter
  • 输入格式化器:继承TextInputformatter
  • 将输入输出格式化器添加到集合中

7.6 Implementing a Custom Formatter

public class CsvOutputFormatter : TextOutputFormatter
{
    public CsvOutputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/csv"));
        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    protected override bool CanWriteType(Type? type)
    {
        if (typeof(CompanyDto).IsAssignableFrom(type) ||
            typeof(IEnumerable<CompanyDto>).IsAssignableFrom(type))
        {
            return base.CanWriteType(type);
        }

        return false;
    }

    public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext
        context, Encoding selectedEncoding)
    {
        var response = context.HttpContext.Response;
        var buffer = new StringBuilder();
        if (context.Object is IEnumerable<CompanyDto>)
        {
            foreach (var company in (IEnumerable<CompanyDto>)context.Object)
            {
                FormatCsv(buffer, company);
            }
        }
        else
        {
            FormatCsv(buffer, (CompanyDto)context.Object);
        }

        await response.WriteAsync(buffer.ToString());
    }

    private static void FormatCsv(StringBuilder buffer, CompanyDto company)
    {
        buffer.AppendLine($"{company.Id},\"{company.Name},\"{company.FullAddress}\"");
    }
}
  • 在构造函数中,定义这个格式化器支持哪种Media Type
  • CanWriteType方法重写,表明CompanyDto这种类型可以被这个格式化器序列化
  • WriteResponseBodyAsync方法重写,构造响应
  • FormatCsv私有方法,响应的格式化

然后在主项目中注册服务,然后服务器就支持返回text/csv格式

public static IMvcBuilder AddCustomCsvFormatter(this IMvcBuilder builder) =>
        builder.AddMvcOptions(config => config.OutputFormatters.Add(new CsvOutputFormatter()));


// Program.cs
builder.Services.AddControllers(config =>
    {

        config.RespectBrowserAcceptHeader = true;
        config.ReturnHttpNotAcceptable = true;
    })
    .AddXmlDataContractSerializerFormatters()
    .AddCustomCsvFormatter()
    .AddApplicationPart(typeof(AssemblyReference).Assembly);

标签:CORE,ASP,格式化,读书笔记,buffer,true,company,typeof,config
来源: https://www.cnblogs.com/huangwenhao1024/p/16383176.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有