在asp.net core中将JSON字符串转换为JsonResult

最近使用core3.1做webapi接口使用实体类输出参数发现要不就使用stirng返回,不能使用JsonResult 输出实体类

return new JsonResult(string)

但是发现出参不是 application/json 而是 text

以下是正确办法

string strJson = Newtonsoft.Json.JsonConvert.SerializeObject(classOutJson);
return new ContentResult { Content = strJson, ContentType = "application/json" };

 

可以通过自定义一个中间件来实现 ASP.NET Core WebApi 返回统一格式参数的需求,下面是一个简单的实现方式: 1. 首先创建一个类来表示统一的返回格式,如下所示: ``` public class ApiResponse<T> { public int Code { get; set; } public string Message { get; set; } public T Data { get; set; } } ``` 其中,Code 表示返回码,Message 表示返回信息,Data 表示返回数据。 2. 创建一个中间件来处理返回结果,如下所示: ``` public class ApiResponseMiddleware { private readonly RequestDelegate _next; public ApiResponseMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { // 执行后续中间件 await _next(context); // 如果返回的是 JsonResult 类型,则对返回结果进行处理 if (context.Response.ContentType == "application/json") { var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; // 读取原始返回结果 var streamReader = new StreamReader(context.Response.Body); var responseBodyText = await streamReader.ReadToEndAsync(); context.Response.Body.Seek(0, SeekOrigin.Begin); // 将原始返回结果反序列化为 ApiResponse 类型 var result = JsonConvert.DeserializeObject<ApiResponse<object>>(responseBodyText, jsonSerializerSettings); // 将 Null 替换为空字符串 result.Data = result.Data ?? string.Empty; // 将 ApiResponse 类型序列化为 Json 字符串 var newResponseBody = JsonConvert.SerializeObject(result); // 将处理后的结果写入 Response 中 using (var sw = new StreamWriter(context.Response.Body)) { sw.Write(newResponseBody); } } } } } ``` 3. 在 Startup.cs 文件的 Configure 方法中添加中间件,如下所示: ``` public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 省略其他代码... app.UseMiddleware<ApiResponseMiddleware>(); // 省略其他代码... } ``` 这样就可以实现 ASP.NET Core WebApi 返回统一格式参数的需求,并且将返回结果中的 Null 替换为空字符串
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值