это мой класс конвертера расширений с использованием JsonConverter в .NET 6
Код: Выделить всё
using System.Text;
using PAP.Echo.Application.Query.Contract.Const;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web;
using System.Net.Http;
namespace PAP.Echo.Application.Query.Contract.JsonConverters;
public class CoverImageExtensionConverter : JsonConverter
{
public CoverImageExtensionConverter()
{
}
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetString();
}
public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
{
var url =$"{WebConfigHelper.CoverImageUrl}";
if (value != null)
{
value = HttpUtility.UrlPathEncode(value);
if (WebConfigHelper.SavePicInWebpFormatIsEnable)
value = AppendWebpExtension(value);
}
writer.WriteStringValue($"{url}{value}");
}
private static string AppendWebpExtension(string value)
{
var extension = Path.GetExtension(value);
if (extension == ImageExtensionConst.Svg)
return value; // Do nothing for SVG files
return $"{Path.GetFileNameWithoutExtension(value)}.{ImageExtensionConst.Webp}";
}
}
Код: Выделить всё
using System;
using System.IO;
using PAP.Echo.Application.Query.Contract.Const;
using System.Web;
using Newtonsoft.Json;
namespace PAP.Echo.Application.Query.Contract.JsonConverters
{
public class CoverImageExtensionConverter : JsonConverter
{
public CoverImageExtensionConverter()
{
}
public override void WriteJson(JsonWriter writer, string? value, JsonSerializer serializer)
{
var url = $"{WebConfigHelper.CoverImageUrl}";
if (value != null)
{
value = HttpUtility.UrlPathEncode(value);
if (WebConfigHelper.SavePicInWebpFormatIsEnable)
value = AppendWebpExtension(value);
}
writer.WriteValue($"{url}{value}");
}
public override string? ReadJson(JsonReader reader, Type objectType, string? existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
return reader.Value.ToString();
}
private static string AppendWebpExtension(string value)
{
var extension = Path.GetExtension(value);
if (extension == ImageExtensionConst.Svg)
return value; // Do nothing for SVG files
return $"{Path.GetFileNameWithoutExtension(value)}.{ImageExtensionConst.Webp}";
}
}
}
Код: Выделить всё
public class PictureDto
{
public string? Title { get; set; }
[JsonConverter(typeof(CoverImageExtensionConverter))]
public string Source { get; set; }
public string? AltText { get; set; }
}
Подробнее здесь: https://stackoverflow.com/questions/783 ... andard-2-1
Мобильная версия