public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
#region Newtonsoft.json替换为Json
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
//忽略循环引用,如果设置为Error,则遇到循环引用的时候报错
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Newtonsoft.Json.Formatting.Indented,
//小驼峰命名法
ContractResolver = new CamelCasePropertyNamesContractResolver(),
//格式化日期时间
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateFormatString = "yyyy-MM-dd HH:mm:ss",
//空值处理
NullValueHandling = NullValueHandling.Ignore
};
#endregion
#region enable CORS
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*"); //http://localhost:13713
config.EnableCors(cors);
#endregion
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{phoneNum}",
defaults: new { phoneNum = RouteParameter.Optional }
);
}
}