Skip to content

Commit

Permalink
支持通信内部控制IJsonHost
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Jun 25, 2024
1 parent ebbbd56 commit 0191d71
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 35 deletions.
7 changes: 6 additions & 1 deletion NewLife.Remoting/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using NewLife.Model;
using NewLife.Net;
using NewLife.Remoting.Http;
using NewLife.Serialization;
using NewLife.Threading;
#if !NET40
using TaskEx = System.Threading.Tasks.Task;
Expand Down Expand Up @@ -46,6 +47,9 @@ public class ApiClient : ApiHost, IApiClient
/// <summary>收到请求或响应时</summary>
public event EventHandler<ApiReceivedEventArgs>? Received;

/// <summary>服务提供者。创建控制器实例时使用,可实现依赖注入。务必在注册控制器之前设置该属性</summary>
public IServiceProvider? ServiceProvider { get; set; }

/// <summary>调用统计</summary>
public ICounter? StatInvoke { get; set; }
#endregion
Expand Down Expand Up @@ -89,7 +93,8 @@ public virtual Boolean Open()
var ss = Servers;
if (ss == null || ss.Length == 0) throw new ArgumentNullException(nameof(Servers), "未指定服务端地址");

Encoder ??= new JsonEncoder();
var json = ServiceProvider?.GetService<IJsonHost>() ?? JsonHelper.Default;
Encoder ??= new JsonEncoder { JsonHost = json };

// 集群
Cluster = InitCluster();
Expand Down
9 changes: 6 additions & 3 deletions NewLife.Remoting/ApiHttpServer.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using NewLife.Http;
using NewLife.Model;
using NewLife.Net;
using NewLife.Remoting.Http;
using NewLife.Serialization;
using HttpCodec = NewLife.Remoting.Http.HttpCodec;

namespace NewLife.Remoting;
Expand Down Expand Up @@ -29,13 +30,15 @@ public override Boolean Init(Object config, IApiHost host)
if (config is NetUri uri) Port = uri.Port;

//RawUrl = uri + "";
var json = ServiceProvider?.GetService<IJsonHost>() ?? JsonHelper.Default;

// Http封包协议
//Add<HttpCodec>();
Add(new HttpCodec { AllowParseHeader = true });
Add(new HttpCodec { AllowParseHeader = true, JsonHost = json });

//host.Handler = new ApiHttpHandler { Host = host };
host.Encoder = new HttpEncoder();

host.Encoder = new HttpEncoder { JsonHost = json };

return true;
}
Expand Down
10 changes: 6 additions & 4 deletions NewLife.Remoting/ApiNetServer.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using NewLife.Http;
using NewLife.Log;
using NewLife.Log;
using NewLife.Messaging;
using NewLife.Model;
using NewLife.Net;
using NewLife.Remoting.Http;
using NewLife.Serialization;
using HttpCodec = NewLife.Remoting.Http.HttpCodec;

namespace NewLife.Remoting;
Expand Down Expand Up @@ -38,9 +39,10 @@ public virtual Boolean Init(Object config, IApiHost host)
// Add<WebSocketServerCodec>();
//else
// Add(new HttpCodec { AllowParseHeader = true });

var json = ServiceProvider?.GetService<IJsonHost>() ?? JsonHelper.Default;

Add<WebSocketServerCodec>();
Add(new HttpCodec { AllowParseHeader = true });
Add(new HttpCodec { AllowParseHeader = true, JsonHost = json });

// 新生命标准网络封包协议
Add(Host.GetMessageCodec());
Expand Down
6 changes: 4 additions & 2 deletions NewLife.Remoting/ApiServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using NewLife.Messaging;
using NewLife.Model;
using NewLife.Net;
using NewLife.Serialization;
using NewLife.Threading;

namespace NewLife.Remoting;
Expand Down Expand Up @@ -47,7 +48,7 @@ public class ApiServer : ApiHost, IServer
public event EventHandler<ApiReceivedEventArgs>? Received;

/// <summary>服务提供者。创建控制器实例时使用,可实现依赖注入。务必在注册控制器之前设置该属性</summary>
public IServiceProvider? ServiceProvider { get; set; } //= ObjectContainer.Provider;
public IServiceProvider? ServiceProvider { get; set; }

/// <summary>处理统计</summary>
public ICounter? StatProcess { get; set; }
Expand Down Expand Up @@ -167,7 +168,8 @@ public virtual void Start()
{
if (Active) return;

Encoder ??= new JsonEncoder();
var json = ServiceProvider?.GetService<IJsonHost>() ?? JsonHelper.Default;
Encoder ??= new JsonEncoder { JsonHost = json };
Handler ??= new ApiHandler { Host = this };

Encoder.Log = EncoderLog;
Expand Down
11 changes: 6 additions & 5 deletions NewLife.Remoting/Http/HttpCodec.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
using System;
using System.Collections.Generic;
using NewLife.Data;
using NewLife.Data;
using NewLife.Http;
using NewLife.Messaging;
using NewLife.Model;
using NewLife.Net;
using NewLife.Serialization;

namespace NewLife.Remoting.Http;

Expand All @@ -17,6 +15,9 @@ public class HttpCodec : Handler
/// 分析头部对性能有一定损耗
/// </remarks>
public Boolean AllowParseHeader { get; set; }

/// <summary>Json主机。提供序列化能力</summary>
public IJsonHost JsonHost { get; set; } = JsonHelper.Default;
#endregion

/// <summary>写入数据</summary>
Expand Down Expand Up @@ -58,7 +59,7 @@ public class HttpCodec : Handler
// 第一个请求必须是GET/POST,才执行后续操作
if (!isGet && !isPost) return base.Read(context, message);

ext["Encoder"] = new HttpEncoder();
ext["Encoder"] = new HttpEncoder { JsonHost = JsonHost };
}

// 检查是否有未完成消息
Expand Down
13 changes: 7 additions & 6 deletions NewLife.Remoting/Http/HttpEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ namespace NewLife.Http;
public class HttpEncoder : EncoderBase, IEncoder
{
#region 属性
/// <summary>Json主机。提供序列化能力</summary>
public IJsonHost JsonHost { get; set; } = JsonHelper.Default;

/// <summary>是否使用Http状态。默认false,使用json包装响应码</summary>
public Boolean UseHttpStatus { get; set; }
#endregion
Expand All @@ -34,11 +37,9 @@ public class HttpEncoder : EncoderBase, IEncoder

if (value == null) return null;

String json;
if (UseHttpStatus)
json = value.ToJson(false, false, false);
else
json = new { action, code, data = value }.ToJson(false, true, false);
var json = UseHttpStatus ?
JsonHost.Write(value, false, false, false) :
JsonHost.Write(new { action, code, data = value }, false, true, false);
WriteLog("{0}=>{1}", action, json);

return json.GetBytes();
Expand Down Expand Up @@ -124,7 +125,7 @@ public class HttpEncoder : EncoderBase, IEncoder
/// <param name="obj"></param>
/// <param name="targetType"></param>
/// <returns></returns>
public virtual Object? Convert(Object obj, Type targetType) => JsonHelper.Default.Convert(obj, targetType);
public virtual Object? Convert(Object obj, Type targetType) => JsonHost.Convert(obj, targetType);

#region 编码/解码
/// <summary>创建请求</summary>
Expand Down
8 changes: 6 additions & 2 deletions NewLife.Remoting/JsonEncoder.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using NewLife.Data;
using NewLife.Messaging;
using NewLife.Model;
using NewLife.Reflection;
using NewLife.Serialization;

Expand All @@ -8,6 +9,9 @@ namespace NewLife.Remoting;
/// <summary>Json编码器</summary>
public class JsonEncoder : EncoderBase, IEncoder
{
/// <summary>Json主机。提供序列化能力</summary>
public IJsonHost JsonHost { get; set; } = JsonHelper.Default;

/// <summary>编码。请求/响应</summary>
/// <param name="action"></param>
/// <param name="code"></param>
Expand Down Expand Up @@ -86,7 +90,7 @@ public virtual Packet Encode(String action, Int32? code, Packet? value)
/// <param name="obj"></param>
/// <param name="targetType"></param>
/// <returns></returns>
public Object? Convert(Object obj, Type targetType) => JsonHelper.Default.Convert(obj, targetType);
public Object? Convert(Object obj, Type targetType) => JsonHost.Convert(obj, targetType);

/// <summary>创建请求</summary>
/// <param name="action"></param>
Expand Down Expand Up @@ -154,7 +158,7 @@ public IMessage CreateResponse(IMessage msg, String action, Int32 code, Object?
if (value is Exception ex)
value = str = ex.GetTrue().Message;
else
str = value.ToJson(false, false, false);
str = JsonHost.Write(value, false, false, false);

pk = str.GetBytes();
}
Expand Down
25 changes: 13 additions & 12 deletions Samples/IoTZero/Common/ApiFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,31 @@ public override void OnActionExecuted(ActionExecutedContext context)
if (context.Result != null)
if (context.Result is ObjectResult obj)
{
var host = context.HttpContext.RequestServices?.GetService<IJsonHost>() ?? JsonHelper.Default;
//context.Result = new JsonResult(new { code = obj.StatusCode ?? 0, data = obj.Value });
var rs = new { code = obj.StatusCode ?? 0, data = obj.Value, traceId };
context.Result = new ContentResult
{
Content = rs.ToJson(false, true, true),
Content = host.Write(rs, false, true, true),
ContentType = "application/json",
StatusCode = 200
};
}
else if (context.Result is EmptyResult)
context.Result = new JsonResult(new { code = 0, data = new { }, traceId });
else if (context.Exception != null && !context.ExceptionHandled)
{
var ex = context.Exception.GetTrue();
if (ex is NewLife.Remoting.ApiException aex)
context.Result = new JsonResult(new { code = aex.Code, data = aex.Message, traceId });
else
context.Result = new JsonResult(new { code = 500, data = ex.Message, traceId });
else if (context.Exception != null && !context.ExceptionHandled)
{
var ex = context.Exception.GetTrue();
if (ex is NewLife.Remoting.ApiException aex)
context.Result = new JsonResult(new { code = aex.Code, data = aex.Message, traceId });
else
context.Result = new JsonResult(new { code = 500, data = ex.Message, traceId });

context.ExceptionHandled = true;
context.ExceptionHandled = true;

// 输出异常日志
if (XTrace.Debug) XTrace.WriteException(ex);
}
// 输出异常日志
if (XTrace.Debug) XTrace.WriteException(ex);
}

base.OnActionExecuted(context);
}
Expand Down

0 comments on commit 0191d71

Please sign in to comment.