c# - 如何在json请求中路由方法
问题描述
我正在为使用 API 的客户端在 Core 上编写服务器。他没有路线。只有IP和端口。但是在 json body 中,我必须实现的方法有一个名称。
要求:
POST / HTTP/1.1
Accept: application/json
Api-Version: 10
Authorization: Bearer 111111111
Content-Type: application/json; charset=utf-8
Host: 127.0.0.1:5050
Content-Length: 104
Connection: Close
{
"UniqueRequestId": null,
"Method": "GetPumpState",
"Data": { "PumpNumber": 1 }
}
我不知道如何实现这一点。如何从请求中获取标签“方法”,路由到控制器中的方法。
解决方案
当您想使用控制器路由时。您可以使用中间件拦截请求并将您的Body
路由转换为控制器路由。
您应该解析请求正文并使用Method
值更新上下文以匹配控制器路由,该路由应以/
. Data
然后,如果您不想打扰控制器中的额外数据,则可以替换当前的正文流。
下面的代码可以给你一些想法。它转换请求正文并仅将数据内容发送到控制器路由。
public class RouteMiddleWare
{
private readonly RequestDelegate _next;
private readonly ILogger<RouteMiddleWare> _logger;
public RouteMiddleWare(RequestDelegate next, ILogger<RouteMiddleWare> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Method == "POST")
{
var requestBody = new MemoryStream();
context.Request.Body.CopyTo(requestBody);
requestBody.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(requestBody);
try
{
var body = streamReader.ReadToEnd();
var request = JsonConvert.DeserializeObject<Request>(body);
context.Request.Path = request.Method;
context.Request.Body =
new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request.Data)));
using (requestBody) _logger.LogInformation("Request body stream has been replaced");
}
catch (Exception ex)
{
_logger.LogWarning($"Failed to apply route from body: {ex.Message}");
context.Request.Body = requestBody;
}
context.Request.Body.Seek(0, SeekOrigin.Begin);
}
await _next.Invoke(context);
}
class Request
{
public string UniqueRequestId { get; set; }
public string Method { get; set; }
public dynamic Data { get; set; }
}
}
另一方面,最好更改客户端代码以使用正确的路径。
推荐阅读
- r - 选择唯一值
- blueprism - Blue Prism:读取 Windows 的环境变量
- reactjs - 反应路由重定向到正确的路径但不加载内容
- android - Android Studio AVD 模拟器不工作
- maven - 在 unix 机器上安装 apache maven 时存储 m2 文件的位置
- apollo - 在此 Apollo 语法中设置客户端的正确方法
- java - Apache Camel - 如何在 java 中使用属性配置端点
- event-handling - 光滑网格;自己处理单元格中元素的鼠标悬停/悬停事件
- c - scanf(" "); 是什么意思 双引号之间只有一个空格?
- html - 通过 attr 进行 Angular 属性绑定。使用@Attribute 时产生空值