首页 > 解决方案 > 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?

标签: c#asp.netjsonasp.net-mvcasp.net-web-api

解决方案


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


推荐阅读