2017-03-07 28 views
2

我正在爲一個類的十進制類型屬性實現自定義輸出格式化程序,它總是返回兩位小數。 例如:value = 5,那麼它應該是5.00。 我在Asp.net核心中創建了一個自定義OutputFormatter,但是,當我應用CanWriteType的覆蓋時,我的代碼方法(WriteResponseBodyAsync)從未被擊中。如果我刪除了CanWriteType方法,那麼它將命中WriteResponseBodyAsync方法,但context.Object包含所有類,而不僅僅是它的十進制屬性。Asp.Net-Core - OutputFormatter將十進制結果格式化爲兩位小數

如何讓此OutputFormatter在響應中使用所有小數屬性? 任何幫助將不勝感激。

public class CustomDecimalFormatter : OutputFormatter 
{ 
    public string ContentType { get; private set; } 
    public CustomDecimalFormatter(){ 
     ContentType = "application/json"; 
     SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json")); 

     } 

    protected override bool CanWriteType(Type type) 
    { 
     return type == typeof(decimal); 
    } 

    public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) 
    { 
     var response = context.HttpContext.Response; 
     var decimalValue = (decimal)context.Object; 

     var formatted = decimalValue.ToString("F2", CultureInfo.InvariantCulture); 

     using (var writer = new StreamWriter(writeStream)) 
     { 
      writer.Write(formatted); 
     } 

     return Task.FromResult(0); 
    } 
} 
+0

你CanWriteType(類型)方法檢查是否該類型是可空,但你試圖context.Object轉換到十進制。你班裏屬性的類型是什麼,小數或可空? – plushpuffin

+0

它可以是小數?無論如何,我希望它適用於其中任何一個。 –

+0

這應該是「返回類型== typeof(十進制)|| type == typeof(decimal?)」;「在CanWriteType中,並將WriteResponseBodyAsync()中的強制轉換爲「(十進制?)」而不是「(十進制)」,如果它是十進制的,則將它強制轉換爲可空(Nullable)。那麼你只是將它作爲可空的來處理,它可能有或沒有價值。 Nullable <>在其ToString()方法中不接受格式字符串,因此只需執行var formatted = decimalValue.HasValue? decimalValue.Value.ToString(「F2」,CultureInfo.InvarianCulture):string.Empty; – plushpuffin

回答

1

我在您的方法和類代碼中看不到任何問題。但在OutputFormatters列表的開頭處添加您的CustomDecimalFormatter將解決此問題。爲了實現這一目標,在Startup.cs添加此行的代碼ConfigureServices方法:

services.AddMvc(options => { 
       options.OutputFormatters.Insert(0,new CustomDecimalFormatter()); 
      }); 
相關問題