Ejemplo n.º 1
0
        static async Task Acceptor(HttpContext hc, Func <Task> n)
        {
            // 排除WebSockets
            if (hc.WebSockets.IsWebSocketRequest)
            {
                return;
            }
            // 只接受GET/POST
            if (hc.Request.Method != HttpMethods.Get && hc.Request.Method != HttpMethods.Post)
            {
                return;
            }

            IDictionary <string, string> args = new Dictionary <string, string>();

            if (hc.Request.Method == HttpMethods.Post)
            {
                if (hc.Request.Form != null)
                {
                    foreach (var item in hc.Request.Form)
                    {
                        args.Add(item.Key, item.Value);
                    }
                }
            }
            else
            {
                foreach (var item in hc.Request.Query)
                {
                    args.Add(item.Key, item.Value);
                }
            }

            if (!RequestParameterVerification(hc.Request.Headers, args, out ResultCode resultCode))
            {
                hc.Response.ContentType = CommonConstant.CONTENT_TYPE;

                ResultObject resultObject = new ResultObject()
                {
                    Code    = resultCode,
                    Message = resultCode.ToMessage()
                };
                await hc.Response.WriteAsync(JsonConvert.SerializeObject(resultObject), Encoding.UTF8);
            }
            else
            {
                string method = hc.Request.Headers[HeaderKeyConstant.REST_METHOD];
                if (string.IsNullOrEmpty(method))
                {
                    return;
                }

                try
                {
                    ITigerMethod tigerMethod = AssemblyHelper.CreateInstance(method, args);
                    var          h           = new ApiHandler(tigerMethod, hc);
                    await h.EchoLoop();
                }
                catch (Exception ex)
                {
                    hc.Response.ContentType = CommonConstant.CONTENT_TYPE;

                    ResultObject resultObject = new ResultObject()
                    {
                        Code    = ResultCode.CustomError,
                        Message = ResultCode.CustomError.ToMessage(),
                        Data    = $"{ex.Message}:{ex.Source}"
                    };
                    await hc.Response.WriteAsync(JsonConvert.SerializeObject(resultObject), Encoding.UTF8);
                }
            }
        }