如何在JSON请求中路由方法

时间:2019-09-11 07:39:03

标签: 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”,并路由到控制器中的方法。

1 个答案:

答案 0 :(得分:2)

当您想使用控制器路线时。您可以使用middleware来拦截请求,并将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; }
    }
}

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