c# - 如何在 json 请求的方法中路由

标签 c# json api .net-core

我正在 Core 上为使用 API 的客户端编写服务器。他没有路线。只有IP和端口。但在 json 正文中,有一个我必须实现的方法的名称。

请求:

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  } 
}

我不知道如何实现这个。如何从请求中获取“Method”标签,路由到 Controller 中的方法。

最佳答案

当您想要使用 Controller 路线时。您可以使用middleware拦截请求并将您的 Body 路由转换为 Controller 路由。

您应该解析请求正文并使用 Method 值更新上下文以匹配 Controller 路由,该路由应以 / 开头。然后,如果您不想在 Controller 中处理额外的数据,则可以将当前的正文流替换为 Data

下面的代码可以给你一些想法。它转换请求正文并仅将数据内容发送到 Controller 路由。

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; }
    }
}

另一方面,最好更改客户端代码以使用正确的路径。

关于c# - 如何在 json 请求的方法中路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57884326/

相关文章:

android - Firebase 数据库错误 - 反序列化时需要一个映射,但得到了一个类 java.util.ArrayList

swift - 将 NULL 值添加到 httpBody Post 请求 - REST API - Swift

linux - 什么代码不应该写成实时代码?

c# - 反序列化期间 XML 文档 (0, 0) 中存在错误

json - 如何将具有两种不同数据类型的 JSON 数组解析为 Golang 中的结构

c# - 发送图像到 yolo(暗网)并接收对象位置和类型

java - 我只想解析 json,其中部分是 2 两个。但响应所有 json 文件解析

javascript - 如何读取API文档中的函数参数?

c# - 使用 MSMQ 和 SQL Server 的分布式事务,但有时会出现脏读

c# - 带有转换器的 WPF 单选按钮 - 我的所有角色如何变成女性