zoukankan      html  css  js  c++  java
  • MVC 返回对象换成json

    错误界面:

    这个就是返回对象没有转换成json

    就是要再返回的头部添加application/json

    代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Formatting;
    using System.Net.Http.Headers;
    using System.Web;
    
    namespace WorkOrderManage.API.Utility
    {
        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;
            }
            public static DateTime GetTime(string timeStamp)
            {
                DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                long lTime = long.Parse(timeStamp + "0000000");
                TimeSpan toNow = new TimeSpan(lTime);
                return dtStart.Add(toNow);
            }
        }
    }

    再在全局文件Global.asax的Application_start里面添加

                var jsonFormatter = new JsonMediaTypeFormatter();
                GlobalConfiguration.Configuration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

    返回界面

    发现content-type里面有application/json

    或者直接添加

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
  • 相关阅读:
    Windows 7任务栏图标特别说明
    Linux下send函数 Broken pipe错误的解决方法
    C++实现一个简单的异常日志记录类
    C++写日志操作
    VC中设置打开文件的权限为管理员权限
    MFC 注册热键
    监控Tomcat状态及配置AIO(APR)模式
    Tomcat管理功能使用及WEB站点部署
    Tomcat多实例配置
    基于端口主机的虚拟主机
  • 原文地址:https://www.cnblogs.com/hongdada/p/4708838.html
Copyright © 2011-2022 走看看