相关疑难解决方法(0)

在ASP.NET MVC中设置默认的JSON序列化程序

我正在处理已部分转换为MVC的现有应用程序.每当控制器使用JSON ActionResult进行响应时,枚举将作为与字符串名称相对的数字发送.这听起来像默认的序列化程序应该是JSON.Net,它应该发送枚举,因为它们的名称与整数表示相反,但事实并非如此.

我是否缺少将其设置为默认序列化程序的web.config设置?或者是否有其他需要更改的设置?

c# asp.net-mvc json.net asp.net-mvc-4

57
推荐指数
2
解决办法
6万
查看次数

MVC 4中正确的JSON序列化

我想让JSON'正确'序列化(camelCase),并且能够在必要时更改日期格式.

对于Web API,它非常简单 - 在Global.asax中,我执行以下代码

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Run Code Online (Sandbox Code Playgroud)

这个代码在管道级别按照我喜欢的方式处理序列化.

我想在MVC 4中完成同样的事情 - 从控制器操作方法返回的任何JSON都要正确序列化.通过一点搜索,我发现以下代码将引入Global.asax应用程序启动:

HttpConfiguration config = GlobalConfiguration.Configuration;
Int32 index = config.Formatters.IndexOf(config.Formatters.JsonFormatter);
config.Formatters[index] = new JsonMediaTypeFormatter
{
     SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
};
Run Code Online (Sandbox Code Playgroud)

它似乎执行正常,但当我从控制器返回JSON时,它都是PascalCased.我的动作方法的一个简单示例:

private JsonResult GetJsonTest()
{
    var returnData = dataLayer.GetSomeObject();
    return Json(returnData, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

我错了吗?知道如何在管道级别实现这一目标吗?

c# asp.net asp.net-mvc json asp.net-mvc-4

43
推荐指数
3
解决办法
6万
查看次数

更改ASP MVC3中使用的默认JSON序列化程序

我有一个控制器将大型JSON对象返回到jQuery Flot,我想知道用ServiceStack.Text中的那个更快地替换默认的JavaScriptSerializer是多么容易.

如果我可以使用DependencyResolver更改这样的东西会很好,但我想如果一切都解决了,那么它可能会变得很慢.

asp.net-mvc serialization json asp.net-mvc-3

17
推荐指数
2
解决办法
2万
查看次数

从ASP.NET MVC返回null时,jQuery post JSON失败

我使用ASP.NET MVC从jQuery发布JSON,并使用这个小库函数获取一些JSON:

(function($) {
    $.postJson = function(url, data) {
        return $.ajax({
            url: url,

            data: JSON.stringify(data),
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8'
        });
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

显然我会这样称呼:

$('#button').click(function() {
    $.postJson('/controller/action', { Prop1: 'hi', Prop2: 'bye' })
    .done(function(r) { alert('It worked.'); })
    .fail(function(x) { alert('Fail! ' + x.status); });
});
Run Code Online (Sandbox Code Playgroud)

ASP.NET MVC 3和ASP.NET MVC 4支持事物的提交方面(在此之前您需要扩展ASP.NET MVC以处理提交JSON),但我遇到的问题是返回.在控制器上我经常返回null,基本上说"成功,没别的说",如:

[HttpPost]
public JsonResult DoSomething(string Prop1, string Prop2)
{
    if (doSomething(Prop1, Prop2)
        return Json(null); // Success

    return Json(new { Message = "It didn't work for …
Run Code Online (Sandbox Code Playgroud)

ajax asp.net-mvc null jquery json

14
推荐指数
1
解决办法
2万
查看次数

如何将JSON.NET作为ASP.NET MVC控制器的模型绑定器?

ASP.NET Web API团队已决定将JSON.NET库用于模型绑定JSON数据.但是,"普通"MVC控制器仍然使用劣质JsonDataContractSerializer.这会导致解析日期的问题,并且让我很头疼.

请参阅此参考:http:
//www.devcurry.com/2013/04/json-dates-are-different-in-aspnet-mvc.html

作者选择在客户端的Knockout层中解决问题.但我更愿意通过在MVC控制器中使用与Web API控制器中相同的JSON.NET模型绑定器来解决此问题.

如何将不同的JSON模型绑定器替换为ASP.NET MVC?具体来说,就是JSON.NET库.如果可能,使用Web API中的相同模型绑定器将是理想的.

asp.net-mvc json model-binding

12
推荐指数
1
解决办法
4981
查看次数

如何在ASP.NET MVC 3+应用程序中使用Json.NET作为默认反序列化器?

关于如何将Json.NET库替换为ASP.NET MVC应用程序中的默认序列化程序有很多资源,但是,就我而言,我找不到一个如何将其设置为默认反序列化器.

为了说明这一点,这里是一些模板代码:

                              // how to use Json.NET when deserializing
                              // incoming arguments?
                                    V
public ActionResult SomeAction ( Foo foo ) {

    // this piece of code has lots of resources
    // on how to override the default Javascript serializer
    return Json(new Bar());

}
Run Code Online (Sandbox Code Playgroud)

如何在控制器操作中反序列化传入参数(例如,从jQuery AJAX调用)时,如何告诉我的应用程序使用Json.NET?

$.ajax({
    type : 'POST',
    data : { foo : 'bar' }
});
Run Code Online (Sandbox Code Playgroud)

我已经尝试MediaTypeFormatters通过从Rick Strahl调整此资源来适应我的代码,但这也不起作用.请注意,我不在WebAPI环境中 - 但我希望一个适用于正常的解决方案Controller应该可以工作(虽然只需要很少的调整)ApiController.

json.net asp.net-mvc-3

11
推荐指数
1
解决办法
3651
查看次数

序列化"System.Reflection"类型的对象时检测到循环引用

我有一个像这样的asp.net MVC 3控制器动作方法:

public JsonResult GetRecordingRates(int Id)
{            
    List<DefaultRateChart> defaultRateCharts = new List<DefaultRateChart>();
    using (IDefaultRateChartManager defaultRateChartManager = new ManagerFactory().GetDefaultRateChartManager()) {
       defaultRateCharts = defaultRateChartManager.GetAll().Where(rc => rc.Currency.Id == Id && (!rc.NumberPrefix.StartsWith("#") || rc.NumberPrefix.StartsWith("Default")) && rc.AccountCredit == "Credit").ToList();
    }
    return Json(defaultRateCharts);
}
Run Code Online (Sandbox Code Playgroud)

我想将此列表发送到jquery ajax成功方法,但我收到 500内部服务器错误

我的ajax调用是这样的:

$.ajax({
type: "POST",
dataType: "json",
url: "/Home/GetRecordingRates",
data: {
    Id: $("#hdCurrencyId").val()                 
},
success: function (data) {
        alert(data);
   }
}); 
Run Code Online (Sandbox Code Playgroud)

在响应标签下的firebug XHR中,它说:

序列化"System.Reflection.RuntimeModule"类型的对象时检测到循环引用.

[编辑]

我将动作方法更改为:

public JsonResult GetRecordingRates(int Id)
{
    List<DefaultRateChart> defaultRateCharts = new List<DefaultRateChart>();
    using (IDefaultRateChartManager defaultRateChartManager …
Run Code Online (Sandbox Code Playgroud)

asp.net ajax jquery json asp.net-mvc-3

10
推荐指数
1
解决办法
2万
查看次数

在控制器级别设置NullValueHandling

暂时的部分,我想从我的api响应中排除空值,所以在我的startup.cs文件中,我有这个.

services.AddMvc()
    .AddJsonOptions(options =>
    {
        // Setup json serializer
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
    });
Run Code Online (Sandbox Code Playgroud)

但是有可能声明在一个或多个控制器上,我实际上想要包含NULL值吗?

c# asp.net json.net asp.net-core

10
推荐指数
1
解决办法
1167
查看次数

JSON.NET - IgnoreDataMember的只读属性和支持

JSON.NET是否支持该IgnoreDataMember属性,还是必须使用JsonIgnore?这是否会在未来得到支持?

另外我发现JSON.NET正在序列化只获取的属性 - 这是预期的行为吗?这是我们可以在串行器级别关闭的东西吗?

json.net

4
推荐指数
1
解决办法
2227
查看次数

浏览器,时区,Chrome 67错误

我已将Chrome更新为67版.我收到日期错误

==============

Microsoft Edge 42.17134.1.0

new Date("1900-01-01T00:00:00").getTimezoneOffset() 

-180

new Date("2018-05-30T00:00:00").getTimezoneOffset()

-180
Run Code Online (Sandbox Code Playgroud)

Microsoft Internet Explorer 11.48.17134.0

new Date("1900-01-01T00:00:00").getTimezoneOffset() 

-180


new Date("2018-05-30T00:00:00").getTimezoneOffset() 

-180
Run Code Online (Sandbox Code Playgroud)

Mozilla Firefox 60.0.1

new Date("1900-01-01T00:00:00").getTimezoneOffset() 

-180

new Date("2018-05-30T00:00:00").getTimezoneOffset() 

-180
Run Code Online (Sandbox Code Playgroud)

Chrome 67.0.3396.62

new Date("1900-01-01T00:00:00").getTimezoneOffset() 

-150

new Date("2018-05-30T00:00:00").getTimezoneOffset()

-180
Run Code Online (Sandbox Code Playgroud)

======================

Chrome 67中的-150 ...

另一个例子(Chrome 67):

new Date("1900-01-01T00:00:00");

Mon Jan 01 1900 00:00:00 GMT+0230 (Moscow Standard Time)
Run Code Online (Sandbox Code Playgroud)

======================

使用Chrome 67时,时区开始不正确(+ 0230,原因是:+0300)

请告诉我?

我能做什么 ?

情况非常重要!我必须重写的所有代码......

======================

javascript browser datetime date

4
推荐指数
1
解决办法
2962
查看次数

Controller返回列表对象的类型名称,而不是列表中的内容

我有简单的代码,我试图从控制器方法返回列表对象,并在浏览器上显示它.相反,浏览器将列表类型显示为:

System.Collections.Generic.List`1[System.String]
Run Code Online (Sandbox Code Playgroud)

以下是我的代码:

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Web.Http;
using System.Web.Script.Serialization;
using MvcApplication2.Models;
using Newtonsoft.Json;

namespace MvcApplication2.Controllers
{
    public class CodesController : Controller
    {
        WebClient myclient = new WebClient();

        public IEnumerable<Codes> Get()
        {
            string data = myclient.DownloadString("URL");
            List<Codes> myobj = (List<Codes>)JsonConvert.DeserializeObject(data, typeof(List<Codes>));
            return myobj;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

DataModel中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication2.Models
{
    public class Codes
    {
        public string hr { get; set; }
        public …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc

3
推荐指数
1
解决办法
3272
查看次数

webapi 中的错误 - 无法从“System.Web.Mvc.JsonRequestBehavior”转换为“Newtonsoft.Json.JsonSerializerSettings”

在 webapi jsonrequestbehaviour 中不起作用,显示无法将“System.Web.Mvc.JsonRequestBehavior”转换为“Newtonsoft.Json.JsonSerializerSettings”

代码

 public ActionResult AddTemprature(string EmployeeName, int EmployeeId, string Location)
        {
            try
            {

                using (EmployeeDBEntities DB = new EmployeeDBEntities())
                {

                    WebApi.Employee emp = new WebApi.Employee();
                    // EmployeeModel Emp = new EmployeeModel();
                    emp.EmpName = EmployeeName;
                    emp.EmpId = EmployeeId;
                    emp.EmpLocation = Location;
                    DB.Employees.Add(emp);
                    DB.SaveChanges();
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception Ex)
            {

            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc json asp.net-mvc-4 asp.net-web-api

1
推荐指数
1
解决办法
5408
查看次数