首页 > 解决方案 > 如何在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  } 
}

我不知道如何实现这一点。如何从请求中获取标签“方法”,路由到控制器中的方法。

标签: c#jsonapi.net-core

解决方案


当您想使用控制器路由时。您可以使用中间件拦截请求并将您的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; }
    }
}

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


推荐阅读