2016-09-26 33 views
2

在asp.net mvc 5中對HttpClient使用PutAsJsonAsync擴展方法返回自檢參考循環檢測到的異常。使用HttpClient PutAsJsonAsync Extension檢測到的自回參考循環

這裏是調用代碼:

httpClient.BaseAddress = _uri; 
HttpResponseMessage response = await httpClient.PutAsJsonAsync<b>("index/1",b); 
response.EnsureSuccessStatusCode(); 

對象B不會具有自參考。

所以我的問題是如何在一個asp.net mvc 5應用程序中設置SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore

回答

2

解決此問題的一種方法是從使用PutAsJsonAsync擴展方法更改爲使用PutAsync擴展方法並明確設置MediaTypeformatter。

var jsonformatter = new JsonMediaTypeFormatter(); 
jsonformatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 

HttpResponseMessage response = await httpClient.PutAsync<b>("index/1",b,jsonformatter); 
response.EnsureSuccessStatusCode(); 

這允許您使用任何您需要的設置。