.Net基于MVC4 Web Api输出Json格式实例

Xanthe ·
更新时间:2024-09-21
· 744 次阅读

本文实例讲述了.Net基于MVC4 Web Api输出Json格式的方法,分享给大家供大家参考。具体实现方法如下:

1、Global 中增加json输出

代码如下: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);
}

2、Global 中删除xml解析

代码如下: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的解析 当返回值是string 时 直接返回string不是json对象
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}

3、指定返回格式

新建方法 需要程序集:
代码如下:System.Web.Extensions
public static HttpResponseMessage ToJson(Object obj)
{
    String str;
    if (obj is String || obj is Char)
    {
        str = obj.ToString();
    }
    else
    {
        var serializer = new JavaScriptSerializer();
        str = serializer.Serialize(obj);
    }
    var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
    return result;
}

 调用户方法转换为json对象输出

代码如下:public HttpResponseMessage GetString(string name)
{
     return ToJson(name);
}

4、重写默认实现类 所有输出将被重新解析成 json

新建JsonContentNegotiator 类
代码如下:public class JsonContentNegotiator : IContentNegotiator
{
    private readonly JsonMediaTypeFormatter _jsonFormatter;
    public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
    {
        _jsonFormatter = formatter;
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {
        var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
        return result;
    }
}

WebApiConfig中使用重写
代码如下: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));

    // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
    // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
    // 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。
    //config.EnableQuerySupport();

    // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
    // 有关详细信息,请参阅: http://www.asp.net/web-api
    config.EnableSystemDiagnosticsTracing();
}

希望本文所述对大家的asp.net程序设计有所帮助。

您可能感兴趣的文章:js遍历json的key和value的实例微信小程序通过api接口将json数据展现到小程序示例Bootstrap 填充Json数据的实例代码简单谈谈MySQL5.7 JSON格式检索JSON在ASP.NET中使用方法ASP.NET中实现把Json数据转换为ADO.NET DataSet对象Asp.net配合easyui实现返回json数据实例ASP.NET中MVC使用AJAX调用JsonResult方法并返回自定义错误信息浅谈C#.NET、JavaScript和JSONjs实现将json数组显示前台table中



net json格式 .NET Web JSON MVC api

需要 登录 后方可回复, 如果你还没有账号请 注册新账号