【发布时间】:2022-02-17 09:44:48
【问题描述】:
我有一个如下所示的 CustomJsonResult 类,它是用 ASP.NET MVC 编写的:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace Web.Authentication
{
public class CustomJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
}
}
我将其转换为 ASP.NET Core MVC。为此,我将 HttpResponseBase 更改为 HttpResponse 并添加了此命名空间 using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace Web.Authentication
{
public class CustomJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponse response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
}
}
我在控制器 json 方法中使用这个类:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult GetDataRefreshDate()
{
var response = ...
return new CustomJsonResult()
{
Data = response,
MaxJsonLength = 86753090
};
}
但转换后,我收到类似的错误
命名空间“System.Web”中不存在类型或命名空间名称“Script”(您是否缺少程序集引用?)
当前上下文中不存在名称“数据”
“HttpResponse”不包含“Write”的定义,并且找不到接受“HttpResponse”类型的第一个参数的可访问扩展方法“Write”(您是否缺少 using 指令或程序集引用?)
当前上下文中不存在名称“ContentEncoding”
'CustomJsonResult.ExecuteResult(ControllerContext)': 找不到合适的方法来覆盖
【问题讨论】:
-
您确定您需要此代码吗?自 Web API 1.0 起,日期使用 ISO8601 格式进行序列化。这是所有 .NET Core 应用程序的默认格式,包括 ASP.NET Core MVC
标签: c# asp.net-mvc asp.net-core-mvc