Asp.net-Web-Api
僅對特定操作使用駝峰式序列化
我使用 WebAPI 已經有一段時間了,通常將其設置為使用駝峰式 json 序列化,這現在很常見,並且到處都有很好的文件記錄。
然而,最近在做一個更大的項目時,我遇到了一個更具體的要求:我們需要使用駝峰式 json 序列化,但是由於我們客戶端腳本的向後兼容性問題,我只希望它發生在特定的操作上,以避免破壞(非常大的)網站的其他部分。
我認為一種選擇是擁有自定義內容類型,但這需要客戶端程式碼來指定它。
還有其他選擇嗎?
謝謝!
試試這個:
public class CamelCasingFilterAttribute : ActionFilterAttribute { private JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter(); public CamelCasingFilterAttribute() { _camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { ObjectContent content = actionExecutedContext.Response.Content as ObjectContent; if (content != null) { if (content.Formatter is JsonMediaTypeFormatter) { actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, _camelCasingFormatter); } } } }應用這個
$$ CamelCasingFilter $$歸因於您想要駝峰式大小寫的任何操作。它將接收您要發回的任何 JSON 響應,並將其轉換為使用駝峰式大小寫來代替屬性名稱。