【问题标题】:How to route in method on json request如何在json请求中路由方法
【发布时间】:2019-09-11 07:39:03
【问题描述】:

我正在为使用 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# json api .net-core


    【解决方案1】:

    当您想使用控制器路由时。您可以使用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; }
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 2019-04-03
      • 2015-11-08
      • 2019-04-07
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多