[英]How to fix this webapi routing configuration?
我在 WebApiConfig.cs 中編寫了這段代碼,但它的行為不符合預期。 例如:json 的駱駝外殼,不包括 null 值的屬性。
我需要指導才能在下面的代碼段中找到任何缺失或不正確的代碼。
這是一個帶有 WebApiConfig.cs 的 web 應用程序,我正在嘗試配置 json 的駱駝套管,並從響應中排除 null 值的屬性。
目前,響應 object 沒有 json 的駱駝外殼,並且包括具有 null 值的屬性。
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
jsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Add(jsonFormatter);
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
提前感謝您的幫助。
使用傳入注冊方法的HttpConfiguration
。
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.Remove(config.Formatters.XmlFormatter);
var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
jsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.