2017-08-27 32 views
-1

我有位指示方法簡單的.NET芯WEP API應用這樣如何從C#.net core web api中刪除BOM JsonResult響應?

[HttpGet("{id}")] 
    public ActionResult Get(int id) 
    { 
     var myObj= _testRepository.TryGetById(id); 
     if (myObj== null) 
     { 
      return new NotFoundResult(); 
     } 
     return new JsonResult(myObj); 

    } 

curl -ivs --raw該方法返回與BOM符號JSON響應。

響應例如:

92 
{"id":767,"gender":"f","birth_date":-278121600} 
0 

如何從響應刪除BOM?

UPDATE

完全響應例如:

HTTP/1.1 200 OK 
Date: Sat, 26 Aug 2017 12:28:58 GMT 
Content-Type: application/json; charset=utf-8 
Server: Kestrel 
Transfer-Encoding: chunked 

60 
{"id":582,"place":"Площадь","country":"Япония","city":"Ньюква","distance":86} 
0 

其中數字是和不是BOM(我這裏的錯誤)。他們造成的chunked transfer encoding

+0

您使用的是什麼版本的ASP.NET WebAPI和JSON.NET?此行爲是一個錯誤,並在2014年得到修復:https://github.com/aspnet/Mvc/issues/577 – Dai

+0

我正在使用軟件包Microsoft.AspNetCore 1.1.2,Microsoft.AspNetCore,Mvc 1.1.3和Newtonsoft.Json 10.0.3 – Frank59

+0

別擔心你的英文@Frank59,對我來說這似乎很好。如果你可以避免在評論中提到這一點,那將會很棒 - 它不會真的增加手頭的問題,但它確實給志願編輯更多的工作要做。謝謝! – halfer

回答

1

有關物料清單的註釋和JsonResult第一個:JsonResultExecutor使用HttpResponseStreamWriter無論使用何種編碼,它都不會寫入BOM。

現在關於塊傳輸編碼:

大多數客戶已經移除分塊,通常我們關於沒有必要擔心。

還有一些禁用分塊的一些方法:

  1. 可以使用ContentResult而不是JsonResult

    public ActionResult Get(int id) 
    { 
        var myObj= _testRepository.TryGetById(id); 
        if (myObj== null) 
        { 
         return new NotFoundResult(); 
        } 
        return new ContentResult{ContentType="application/json", Content=DoMySerialize(myObj)}; 
    
    } 
    
  2. 您可以完全緩衝響應並確定內容長度。這裏有一個緩衝的所有響應中間件提供 https://github.com/aspnet/BasicMiddleware/blob/793a49fe111d86895f22300297fa70f710459406/src/Microsoft.AspNetCore.Buffering/ResponseBufferingMiddleware.cs#L19

有詳細的註釋裏面question on github樣本。

相關問題