端点路由+ swagger + OData + Swagger

时间:2020-10-07 13:43:09

标签: asp.net-core json.net swagger odata converters

我正在使用以下方法评估.Net 5(此行为在.Net core 3.1中也是相同的):

  • .NET 5预览
  • 端点路由
  • OData 7.5.0
  • 昂首阔步
  • Newtonsoft JSON

由于当前 System.Text.Json 功能的水平会导致对现有JSON转换器的大量返工,因此我非常需要继续使用 Newtonsoft 。 我的启动代码如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddNewtonsoftJson(
            options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.Converters.Add(new InputFieldStatusConverter());
            })
        .AddXmlSerializerFormatters();

    services.AddOData();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });

    SetOutputFormatters(services);
}

输入字段状态转换器如下:

public class InputFieldStatusConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        if (objectType == null)
        {
            return false;
        }
        return true:
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Return false when the objectType object is null 
        if (objectType == null)
        {
            return false;
        }
    }
}

SetOutputFormatters方法:

private static void SetOutputFormatters(IServiceCollection services)
{
    services.AddMvcCore(options =>
    {
        IEnumerable<ODataOutputFormatter> outputFormatters =
            options.OutputFormatters.OfType<ODataOutputFormatter>()
                .Where(foramtter => foramtter.SupportedMediaTypes.Count == 0);

        IEnumerable<ODataInputFormatter> inputFormatters =
            options.InputFormatters.OfType<ODataInputFormatter>()
                .Where(formatter => formatter.SupportedMediaTypes.Count == 0);

        foreach (var outputFormatter in outputFormatters)
        {
            outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/odata"));
        }
        foreach (var inputFormatter in inputFormatters)
        {
            inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/odata"));
        }

    });
}

控制器的装饰如下:

[Route("odata/[controller]")]    
[ApiExplorerSettings(IgnoreApi = false)]
public class WeatherForecastController : ODataController

,动作签名如下:

[HttpPost]
public async Task<IActionResult> Post([FromBody] WeatherForecast wf)

OData和swagger可以正常工作,但是不会触发Newtonsoft转换器。我看到How to add Swagger in OData-enabled Web API running on ASP.NET Core 3.1发布了类似的问题。但是就我而言,草率的文档没有问题,但是Json转换器没有问题。任何潜在客户表示赞赏。

0 个答案:

没有答案