c# - How best to display formatted properties between web api and clients
问题描述
I am converting a MVC 5 ecommerce project to consume WEB API services instead so as to develop a mobile app for it too. I need advice on how best to handle the prices of products. In the current mvc app, the DisplayFormat attribute is working very fine.
[DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false, NullDisplayText = "-")]
public decimal Price { get; set; }
The above displays the currency as expected (e.g. $200.29) but this does not seem to work in web api. It returns just the price digit in decimal. All the business logic now lives in the api. NOW MY QUESTION: Is there a way to send this currency in its formatted type (i.e. displays as currency, e.g. $200.29) from the api directly so I don't have to handle formatting in all the clients that'll use the api such as mobile and web? Or I have to handle the formatting in all the clients?
解决方案
You can write a converter and attach as attribute so during deserialization, the data is returned as per format defined in Converter.
For example, following class represents converting decimal to currency format
internal class CurrencyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(decimal) || objectType == typeof(decimal?));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Decimal? d = value as decimal?;
JToken.FromObject(string.Format("{0:C}", d.GetValueOrDefault())).WriteTo(writer);
}
}
Now the above converter can be applied to property
public class Order
{
public string Item {get; set;}
[JsonConverter(typeof(CurrencyConverter))]
public decimal Price {get; set;}
}
With above when response is returned by WebApi, the property price would be the currency format like shown below
{"Item":"Some Item","Price":"$2.34"}
You can refer to this dotnet fiddle - https://dotnetfiddle.net/c5FTDz
推荐阅读
- amazon-web-services - AWS 如何从私有子网中的 EC2 实例打开网站
- r - 从单元格中删除 R 矩阵 NA
- d3.js - d.label 在 D3 折线图上读取未定义
- python - 将方法传递给 Python 方法
- web - 将数据嵌入到 web 的坐标系中
- webpack - webpack 的(轻微)样式加载延迟
- django - 由于手动将其设置为 python 后构建包不兼容,我正在努力在 Heroku 上部署我的 Django 项目(Django 3.1)
- javascript - 显示从 API 中选择的下拉框项目价格
- python - 使用 PyAudio 和 SpeechRecognition 时出现 ALSA 错误:PaAlsaStreamComponent_BeginPolling: Assertion `ret == self->nfds' failed
- laravel - 基于两个字段的唯一表单验证