微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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,所以在返回的时候,会报错,我们需要对这个类型进行处理

  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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐