GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//添加json 解析 使用方法 http://xxx/api/action?json=true
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//刪除xml的解析 當(dāng)返回值是string 時(shí) 直接返回string不是json對(duì)象
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerableMediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
// 取消注釋下面的代碼行可對(duì)具有 IQueryable 或 IQueryableT> 返回類型的操作啟用查詢支持。
// 若要避免處理意外查詢或惡意查詢,請(qǐng)使用 QueryableAttribute 上的驗(yàn)證設(shè)置來(lái)驗(yàn)證傳入查詢。
// 有關(guān)詳細(xì)信息,請(qǐng)?jiān)L問(wèn) http://go.microsoft.com/fwlink/?LinkId=279712。
//config.EnableQuerySupport();
// 若要在應(yīng)用程序中禁用跟蹤,請(qǐng)注釋掉或刪除以下代碼行
// 有關(guān)詳細(xì)信息,請(qǐng)參閱: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}