.Net基于MVC4 Web Api输出Json格式的方法

发布时间:2021-07-01 09:27:11 作者:chen
来源:亿速云 阅读:114

本篇内容介绍了“.Net基于MVC4 Web Api输出Json格式的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

本文实例讲述了.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();
}

“.Net基于MVC4 Web Api输出Json格式的方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. ASP.NET WebAPI构建API接口服务实战演练
  2. ASP.NET WebApi技术从入门到实战演练

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

json

上一篇:HTML5中i、em、b、strong元素有什么区别

下一篇:cmd批处理中set /a和set /p的区别是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》