Ejemplo n.º 1
0
        private static Dictionary <string, string> GetHeaders(HttpRequestHeaders headers)
        {
            var output = new Dictionary <string, string>();

            foreach (var item in headers.ToList())
            {
                output.Add(item.Key, headers.GetValues(item.Key).First().ToString());
            }
            return(output);
        }
//        public static HttpRequestHeaders ToHttpRequestHeaders(this HeaderCollection headers)
//        {
//            if (headers == null) throw new ArgumentNullException(nameof(headers));
//
//            var rh = HttpRequestHeaders;
//        }

        public static HeaderCollection ToHeaderCollection(this HttpRequestHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            var hc = new HeaderCollection(HttpHeaderType.RequestHeader);

            hc.AddRange(headers.ToList());

            return(hc);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 获取Request的head
        /// </summary>
        /// <param name="headers">
        /// http的head
        /// </param>
        /// <returns>
        /// 返回指定上下文的head
        /// </returns>
        public static Entity.HeaderRequestInfo GetRequestHeadInfo(this
                                                                  HttpRequestHeaders headers)
        {
            Entity.HeaderRequestInfo result;
            try
            {
                var head = headers.ToList();
                result = Convert.ConvertUtility.StringCollectionToEntity <Entity.HeaderRequestInfo>(head);
            }
            catch (Exception)
            {
                result = null;
            }

            return(result);
        }
        public async Task <IHttpActionResult> Handle()
        {
            try
            {
                HttpRequestMessage req        = Request;
                Uri                reqUri     = req.RequestUri;
                HttpMethod         reqMethod  = req.Method;
                HttpContent        reqContent = req.Content;
                HttpRequestHeaders reqHeaders = req.Headers;

                if (Program.basicAuth != null)
                {
                    var auth = reqHeaders.Authorization;
                    if (auth == null)
                    {
                        HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                        res.Headers.Add("WWW-Authenticate", "Basic realm=\"User Visible Realm\"");
                        res.Content = new StringContent("This action requires login.");

                        throw new HttpResponseException(res);
                    }
                    else
                    {
                        string authSource = Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter));
                        string account    = authSource.Substring(0, authSource.IndexOf(":"));
                        string password   = authSource.Substring(authSource.IndexOf(":") + 1, authSource.Length - authSource.IndexOf(":") - 1);

                        if (account != Program.basicAuth?.account || password != Program.basicAuth?.password)
                        {
                            HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                            res.Content = new StringContent("Login failed.");

                            throw new HttpResponseException(res);
                        }
                    }
                }

                List <KeyValuePair <string, IEnumerable <string> > > headers = reqHeaders.ToList().Concat(reqContent.Headers.ToList()).ToList();

                JObject content = new JObject();
                if (reqMethod == HttpMethod.Get || reqMethod == HttpMethod.Delete)
                {
                    NameValueCollection input = HttpUtility.ParseQueryString(reqUri.Query);

                    foreach (var key in input)
                    {
                        List <string> keys    = Regex.Split(key.ToString(), @"\.").ToList();
                        JToken        _JToken = content;
                        for (int i = 0; i < keys.Count(); i++)
                        {
                            if (i == keys.Count() - 1)
                            {
                                _JToken[keys[i]] = input[key.ToString()];
                            }
                            if (_JToken[keys[i]] == null)
                            {
                                _JToken[keys[i]] = new JObject();
                            }
                            _JToken = _JToken[keys[i]];
                        }
                    }
                }
                else if (reqMethod == HttpMethod.Post || reqMethod == HttpMethod.Put)
                {
                    string input = reqContent.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(input))
                    {
                        content = JsonConvert.DeserializeObject <JObject>(input);
                    }
                }

                string info = "";
                info += $"\r\n    Method: {reqMethod.Method}";
                info += $"\r\n    Path: {reqUri.LocalPath}";
                info += $"\r\n    Headers:";
                foreach (var header in headers)
                {
                    if (header.Value == null)
                    {
                        continue;
                    }
                    info += $"\r\n        - {header.Key}: {JsonConvert.SerializeObject(header.Value)}";
                }
                info += $"\r\n    Content:";
                info += IndexController.ContentInfo(content, 0);

                Program.PrintService.Log($"{info}", Print.EMode.message);

                return(Json(content));
            }
            catch (HttpResponseException ex)
            {
                if (ex.Response.Headers.WwwAuthenticate.Count == 0)
                {
                    Program.PrintService.Log($"{ex.Response.StatusCode}, {await ex.Response.Content.ReadAsStringAsync()}", Print.EMode.error);
                }
                else
                {
                    Program.PrintService.Log($"{ex.Response.StatusCode}, {await ex.Response.Content.ReadAsStringAsync()}", Print.EMode.warning);
                }

                return(ResponseMessage(ex.Response));
            }
            catch (Exception ex)
            {
                ex = ExceptionHelper.GetReal(ex);
                Program.PrintService.Log($"{ex.Message}", Print.EMode.error);

                return(Content(HttpStatusCode.InternalServerError, ex.Message));
            }
        }