首先创建一个新的MediaTypeFormatter: 公共类MyDecimalFormatter:MediaTypeFormatter{公共MyDecimalFormatter(){SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));SupportedEncodings.Add(Encoding.UTF8);}公共重写bool CanReadType(Type type){返回false;}公共重写bool CanWriteType(Type type){返回类型== typeof(十进制);}公共重写任务WriteToStreamAsync(Type type,object value,Stream writeStream,HttpContent content,TransportContext transportContext){var decimalValue =(十进制)值;var formatted = decimalValue.ToString("F2",CultureInfo.InvariantCulture);使用(var writer = new StreamWriter(writeStream)){writer.Write(格式化);}返回Task.FromResult(0);}} 然后将其首先添加到Web Api配置中的formatters集合中: config.Formatters.Insert(0,new MyDecimalFormatter()); 您可以将此行添加到 WebApiConfig.cs Register 方法中,或添加到 Global.asax / Startup.cs .此方法与 result.ToString() 之间的区别 在操作中仅使用 .ToString(). 动作: //..十进制结果= GetMyNumber();返回Ok(result.ToString("F2"));//确定收到一个字符串作为参数 HTTP响应正文: "15321.39"//这是JSON字符串,而不是数字 使用自定义 MediaTypeFormatter 动作: //..十进制结果= GetMyNumber();返回Ok(结果);//Ok接受小数点作为参数 HTTP响应正文: 15321.39//这是一个JSON编号 How to format web api decimal result to two decimal spaces?I have a web api method that should return number '15321.39'.However the value returned is 15321.3900My code sample is: [Route("GetDecimalValue")] [ResponseType(typeof(decimal))] [HttpGet] public IHttpActionResult GetDecimal() { try { decimal result = GetMyNumber(); // returns number such as 15321.39 return Ok(result); } catch (Exception ex) { return InternalServerError(ex); } }public decimal GetMyNumber(){ return 15321.39m}Plese note I do not want to change the return type 解决方案 You could try replacing the default formatter (in your case the JsonFormatter) for decimal type with your custom implementation. This is applied globally and for every decimal you will use as parameter of any NegotiatedContentResult (e.g. it will work out of the box for the Ok method in your sample).First create a new MediaTypeFormatter:public class MyDecimalFormatter : MediaTypeFormatter{ public MyDecimalFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); SupportedEncodings.Add(Encoding.UTF8); } public override bool CanReadType(Type type) { return false; } public override bool CanWriteType(Type type) { return type == typeof(decimal); } public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { var decimalValue = (decimal)value; var formatted = decimalValue.ToString("F2", CultureInfo.InvariantCulture); using (var writer = new StreamWriter(writeStream)) { writer.Write(formatted); } return Task.FromResult(0); }}Then add it as first to formatters collection in your Web Api configuration:config.Formatters.Insert(0, new MyDecimalFormatter());You could add this line inside WebApiConfig.cs Register method, or in Global.asax/Startup.cs.Differences between this method and result.ToString()Using just .ToString() inside your action.Action://..decimal result = GetMyNumber();return Ok(result.ToString("F2")); //Ok receives a string as argumentHTTP Response body:"15321.39" //This is a JSON string, not a numberUsing the custom MediaTypeFormatterAction://..decimal result = GetMyNumber();return Ok(result); //Ok recives a decimal as argumentHTTP Response body:15321.39 //This is a JSON number 这篇关于如何将Web API十进制结果格式化为两个十进制空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-22 22:17
查看更多