错误界面:

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));

返回界面

MVC 返回对象换成json

发现content-type里面有application/json

 

或者直接添加

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));

 

相关文章:

  • 2022-02-09
  • 2022-02-09
  • 2022-03-08
  • 2021-06-04
  • 2021-07-18
  • 2021-11-21
  • 2021-08-12
猜你喜欢
  • 2022-02-09
  • 2022-12-23
  • 2021-07-15
  • 2022-02-09
  • 2021-11-05
  • 2022-12-23
  • 2022-02-04
相关资源
相似解决方案