Exemplo n.º 1
0
 /// <summary>
 /// 判断是否是Ajax请求
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public static bool IsAjaxRequest(this Microsoft.AspNetCore.Http.HttpRequest request)
 {
     return(request?.Headers != null && string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.OrdinalIgnoreCase));
 }
 public static Microsoft.AspNetCore.Http.Headers.RequestHeaders GetTypedHeaders(this Microsoft.AspNetCore.Http.HttpRequest request)
 {
     throw null;
 }
 public static string GetMultipartBoundary(this Microsoft.AspNetCore.Http.HttpRequest request)
 {
     throw null;
 }
 public static bool SupportsTrailers(this Microsoft.AspNetCore.Http.HttpRequest request)
 {
     throw null;
 }
Exemplo n.º 5
0
        public DecryptedData Decrypt(Microsoft.AspNetCore.Http.HttpRequest httpRequest, string keyName, string keyId, EncryptedData encryptedData)
        {
            _logger.LogInformation("decrypt called from key manager class for keyName : " + keyName + " and keyID : " + keyId);
            //user.ThrowIfNull(nameof(user));
            string myResponse = "";
            string clearText  = "";


            keyName.ThrowIfNull(nameof(keyName));
            keyId.ThrowIfNull(nameof(keyId));
            encryptedData.ThrowIfNull(nameof(encryptedData));

            string websiteHostName = System.Environment.GetEnvironmentVariable("UKC_SERVER_IP");
            string partition       = System.Environment.GetEnvironmentVariable("UKC_PARTITION");
            //string cipherTextBase64 = "CSYMkVvmsD9e/bLxPoT2c7CSPwM/Y+qJ5PU4vATLRccSdKhECzPg1gNHw67os6o2/H3Y41VN4nR+Augo2aNytqvvc4STqch6PZhF8z8SZgf/MW04KfgVFQQYIEDFQ+QI0B2SrY44wqnqpBN0cClcl1JAJoXAwWDVLm72AML45e3yRJbv7rgWgmLw9uYXrW66E2u9X2nyb5doW+Cxc3/Rrv8b6nGVnhtwnAPj2o0QdDsc7lnLPT2UAG8vImfa5bsG6xHYIe8J723VG6Wm7RqzdHPb9LG1e9EiWG331K+4lPpGInPzgnwsUse0T4NMswo+qcFTVEbC0LFUpgNMmGqhOw==";
            string cipherTextBase64 = encryptedData.Value;

            //create decypt body

            var body = new
            {
                cipher = new
                {
                    cipherTextBase64 = cipherTextBase64
                },
                aSymmetricParams = new
                {
                    padding = new
                    {
                        type = "OAEP",
                        oaep = new
                        {
                            mgf = "SHA256"
                        }
                    },
                },
                outputEncoding = "BASE64"
            };
            // JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            // string json = JsonSerializer.Serialize(body);
            var json = JsonConvert.SerializeObject(body);
            var data = Encoding.ASCII.GetBytes(json);

            //var keyUid = "b0071ba7dc79f9bf";

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://" + websiteHostName + "/api/v1/keys/" + keyId + "/decrypt" + "?partitionId=" + partition);
                request.Method          = "POST";
                request.ContentType     = "application/json; charset=utf-8";
                request.KeepAlive       = true;
                request.PreAuthenticate = true;
                request.Headers.Add("Authorization", getToken(httpRequest));
                request.Accept = "application/json";
                //request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentLength = data.Length;
                request.Headers.Add("Accept", "application/json");
                //request.ContentType = "application/x-www-form-urlencoded";
                request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    //string json = "{ \"method\" : \"guru.test\", \"params\" : [ \"Guru\" ], \"id\" : 123 }";

                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    myResponse = sr.ReadToEnd();
                }
                Console.Write(myResponse);

                JObject jsonObj = JObject.Parse(myResponse);
                clearText = (string)jsonObj.SelectToken("clearText");
                //string modulus = (string)jsonObj.SelectToken("pkInfo.rsa.modulus");
            }
            catch (WebException e)
            {
                _logger.LogInformation("This program is expected to throw WebException on successful run." +
                                       "\n\nException Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    _logger.LogInformation("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    _logger.LogInformation("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    throw e;
                }
            }
            // JObject json = JObject.Parse(myResponse);
            // string accessToken = "";
            // foreach (var e in json)
            // {
            //     if(e.Key=="access_token")
            //     {
            //         accessToken = e.Value.ToString();
            //     }
            // }


            //use ukc to decrypt
            // byte[] keyNameBytes = Encoding.UTF8.GetBytes(keyName);
            // ulong keyUID = (ulong)Convert.ToUInt64(keyId,16);

            // CK_OBJECT_HANDLE pubKey;
            // CK_OBJECT_HANDLE prvKey;
            // CK_OBJECT_HANDLE publicTest;

            // Library.C_Initialize();
            // CK_SLOT_ID[] slots = Library.C_GetSlotList(true);
            // CK_SLOT_ID slot = slots[0];
            // CK_SESSION_HANDLE session = Library.C_OpenSession(slot);

            // Library.C_FindObjectsInit(session, new CK_ATTRIBUTE[]
            // {
            //     new CK_ATTRIBUTE(CK.CKA_TOKEN, true),
            //     new CK_ATTRIBUTE(CK.CKA_CLASS, CK.CKO_PRIVATE_KEY),
            //     new CK_ATTRIBUTE(CK.CKA_KEY_TYPE, CK.CKK_RSA),
            //     //new CK_ATTRIBUTE(CK.CKA_ID, keyNameBytes),
            //     new CK_ATTRIBUTE(CK.DYCKA_UID , keyUID)

            // });

            // CK_OBJECT_HANDLE[] foundKeyHandles = Library.C_FindObjects(session, 1);
            // Library.C_FindObjectsFinal(session);

            // CK_ATTRIBUTE n =  new CK_ATTRIBUTE(CK.CKA_MODULUS);
            // CK_ATTRIBUTE e = new CK_ATTRIBUTE(CK.CKA_PUBLIC_EXPONENT);
            // CK_ATTRIBUTE privateKeyUid =  new CK_ATTRIBUTE(CK.DYCKA_UID);

            // if(foundKeyHandles.Length == 0) throw new Exception("key" + keyName + " not found");

            // //_logger.LogInformation("encryptedData.Value = "  + encryptedData.Value);

            // byte[] plainData = Convert.FromBase64String(encryptedData.Value);

            // CK_RSA_PKCS_OAEP_PARAMS oaepParams = new CK_RSA_PKCS_OAEP_PARAMS();
            // oaepParams.hashAlg = CK.CKM_SHA256;
            // oaepParams.mgf = CK.CKG_MGF1_SHA256;
            // CK_MECHANISM mech_rsa = new CK_MECHANISM(CK.CKM_RSA_PKCS_OAEP, oaepParams);

            // Library.C_DecryptInit(session, mech_rsa, foundKeyHandles[0]);

            // byte[] decrypted = Library.C_Decrypt(session, plainData);



            return(new DecryptedData(clearText));
        }
Exemplo n.º 6
0
        public static async Task <FormData> FromRequest(Microsoft.AspNetCore.Http.HttpRequest request)
        {
            try
            {
                FormData data = new FormData();
                foreach (var kv in request.Query)
                {
                    data.mapParams[kv.Key] = kv.Value[0];
                }
                if (request.Method.ToUpper() == "POST")
                {
                    if (request.ContentType == null)
                    {
                        return(data);
                    }
                    else if (request.ContentType == "application/x-www-form-urlencoded")
                    {
                        byte[] allfile = null;
                        int    seek    = 0;
                        var    _clen   = request.Headers["Content-Length"];
                        string clen    = null;
                        if (_clen.Count > 0)
                        {
                            clen = _clen[0];
                        }
                        if (clen != null)
                        {
                            int leng = int.Parse(clen);
                            allfile = new byte[leng];

                            while (request.Body.CanRead)
                            {
                                int read = await request.Body.ReadAsync(allfile, seek, leng - seek);

                                seek += read;
                                if (read == 0)
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            allfile = new byte[4 * 1024 * 1024];

                            while (request.Body.CanRead)
                            {
                                int read = await request.Body.ReadAsync(allfile, seek, 1024);

                                seek += read;
                                if (read == 0)
                                {
                                    break;
                                }
                            }
                        }


                        string text  = System.Text.Encoding.UTF8.GetString(allfile, 0, seek);
                        var    infos = text.Split(new char[] { '=', '&' });
                        for (var i = 0; i < infos.Length / 2; i++)
                        {
                            data.mapParams[infos[i * 2]] = Uri.UnescapeDataString(infos[i * 2 + 1]);
                        }
                    }
                    else if (request.ContentType.IndexOf("multipart/form-data;") == 0)
                    {
                        byte[] allfile = null;
                        int    seek    = 0;
                        var    _clen   = request.Headers["Content-Length"];
                        string clen    = null;
                        if (_clen.Count > 0)
                        {
                            clen = _clen[0];
                        }
                        if (clen != null)
                        {
                            int leng = int.Parse(clen);
                            allfile = new byte[leng];

                            while (request.Body.CanRead)
                            {
                                int read = await request.Body.ReadAsync(allfile, seek, leng - seek);

                                seek += read;
                                if (read == 0)
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            allfile = new byte[4 * 1024 * 1024];

                            while (request.Body.CanRead)
                            {
                                int read = await request.Body.ReadAsync(allfile, seek, 1024);

                                seek += read;
                                if (read == 0)
                                {
                                    break;
                                }
                            }
                        }


                        var iSplitTag = request.ContentType.IndexOf("=") + 1;
                        var sSplitTag = "--" + request.ContentType.Substring(iSplitTag);
                        var bSplitTag = System.Text.Encoding.ASCII.GetBytes(sSplitTag);

                        int iTag = ByteIndexOf(allfile, seek, bSplitTag, 0);
                        if (iTag < 0)
                        {
                            string s = System.Text.Encoding.ASCII.GetString(allfile, 0, seek);
                        }
                        else
                        {
                            while (iTag >= 0)
                            {
                                int iTagNext = ByteIndexOf(allfile, seek, bSplitTag, iTag + 1);
                                if (iTagNext < 0)
                                {
                                    break;
                                }
                                var           bs         = System.Text.Encoding.ASCII.GetBytes("\r\n\r\n");
                                int           iStart     = iTag + bSplitTag.Length + 2;
                                int           iDataStart = ByteIndexOf(allfile, seek, bs, iStart) + 4;
                                string        s          = System.Text.Encoding.ASCII.GetString(allfile, iStart, iDataStart - iStart);
                                List <string> infos      = new List <string>(s.Split(new string[] { "; ", ": ", "\r\n", "=" }, StringSplitOptions.None));
                                var           i          = infos.IndexOf("name");
                                var           name       = infos[i + 1].Substring(1);
                                name = name.Substring(0, name.Length - 1);

                                byte[] ddata = new byte[iTagNext - iDataStart - 2];
                                Array.Copy(allfile, iDataStart, ddata, 0, ddata.Length);
                                if (infos.Contains("application/octet-stream"))
                                {
                                    data.mapFiles[name] = ddata;
                                }
                                else
                                {
                                    string txtData = System.Text.Encoding.UTF8.GetString(ddata);

                                    data.mapParams[name] = Uri.UnescapeDataString(txtData);
                                }
                                iTag = iTagNext;
                            }
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }
                return(data);
            }
            catch
            {
                return(null);
            }
        }
 public static Microsoft.Extensions.Primitives.StringValues GetDeclaredTrailers(this Microsoft.AspNetCore.Http.HttpRequest request)
 {
     throw null;
 }
Exemplo n.º 8
0
 public static void EnableBuffering(this Microsoft.AspNetCore.Http.HttpRequest request, long bufferLimit)
 {
 }
Exemplo n.º 9
0
 public static System.Threading.Tasks.Task <Microsoft.AspNetCore.Http.IFormCollection> ReadFormAsync(this Microsoft.AspNetCore.Http.HttpRequest request, Microsoft.AspNetCore.Http.Features.FormOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     throw null;
 }
Exemplo n.º 10
0
 public static Microsoft.AspNetCore.Http.HttpRequest EnableRewind(this Microsoft.AspNetCore.Http.HttpRequest request, int bufferThreshold = 30720, long?bufferLimit = default(long?))
 {
     throw null;
 }
Exemplo n.º 11
0
 public static void EnableBuffering(this Microsoft.AspNetCore.Http.HttpRequest request, int bufferThreshold)
 {
 }
Exemplo n.º 12
0
 /// <summary>
 /// Extract token from request
 /// </summary>
 /// <param name="request"></param>
 /// <returns>token</returns>
 public static string GetTokenFromRequest(Microsoft.AspNetCore.Http.HttpRequest request)
 {
     return(request.Headers.FirstOrDefault(h => h.Key == "Authorization").Value);
 }
 public DerivedODataQueryOptions(ODataQueryContext context, Microsoft.AspNetCore.Http.HttpRequest request)
 public override void ValidateQuery(Microsoft.AspNetCore.Http.HttpRequest request, ODataQueryOptions queryOptions)
Exemplo n.º 15
0
 public static System.Threading.Tasks.ValueTask <object> ReadFromJsonAsync(this Microsoft.AspNetCore.Http.HttpRequest request, System.Type type, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) => throw null;
Exemplo n.º 16
0
 public FormFeature(Microsoft.AspNetCore.Http.HttpRequest request)
 {
 }
Exemplo n.º 17
0
 public static System.Threading.Tasks.ValueTask <TValue> ReadFromJsonAsync <TValue>(this Microsoft.AspNetCore.Http.HttpRequest request, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) => throw null;
Exemplo n.º 18
0
 public FormFeature(Microsoft.AspNetCore.Http.HttpRequest request, Microsoft.AspNetCore.Http.Features.FormOptions options)
 {
 }
 public static bool CheckTrailersAvailable(this Microsoft.AspNetCore.Http.HttpRequest request)
 {
     throw null;
 }
Exemplo n.º 20
0
        public static String GetUserPlatform(Microsoft.AspNetCore.Http.HttpRequest request)
        {
            try
            {
                var ua = request.Headers["User-Agent"].ToString();

                if (ua.Contains("Android"))
                {
                    return(string.Format("Android {0}", GetMobileVersion(ua, "Android")));
                }

                if (ua.Contains("iPad"))
                {
                    return(string.Format("iPad OS {0}", GetMobileVersion(ua, "OS")));
                }

                if (ua.Contains("iPhone"))
                {
                    return(string.Format("iPhone OS {0}", GetMobileVersion(ua, "OS")));
                }

                if (ua.Contains("Linux") && ua.Contains("KFAPWI"))
                {
                    return("Kindle Fire");
                }

                if (ua.Contains("RIM Tablet") || (ua.Contains("BB") && ua.Contains("Mobile")))
                {
                    return("Black Berry");
                }

                if (ua.Contains("Windows Phone"))
                {
                    return(string.Format("Windows Phone {0}", GetMobileVersion(ua, "Windows Phone")));
                }

                if (ua.Contains("Mac OS"))
                {
                    return("Mac OS");
                }

                if (ua.Contains("Windows NT 5.1") || ua.Contains("Windows NT 5.2"))
                {
                    return("Windows XP");
                }

                if (ua.Contains("Windows NT 6.0"))
                {
                    return("Windows Vista");
                }

                if (ua.Contains("Windows NT 6.1"))
                {
                    return("Windows 7");
                }

                if (ua.Contains("Windows NT 6.2"))
                {
                    return("Windows 8");
                }

                if (ua.Contains("Windows NT 6.3"))
                {
                    return("Windows 8.1");
                }

                if (ua.Contains("Windows NT 10"))
                {
                    return("Windows 10");
                }

                //fallback to basic platform:
                //return request.Browser.Platform + (ua.Contains("Mobile") ? " Mobile " : "");
                return(ua.Contains("Mobile") ? " Mobile " : "");
            }
            catch (Exception ex)
            {
                string Error = string.Format("{0} - {1} ", ex.Message, ex.InnerException != null ? ex.InnerException.FullMessage() : "");
                //new Helpers.ExceptionLogger().Log("APIs ::  SecurityHelper", "GetUserPlatform", Error, DateTime.Now);
                return("");
            }
        }
 public static Microsoft.Extensions.Primitives.StringValues GetTrailer(this Microsoft.AspNetCore.Http.HttpRequest request, string trailerName)
 {
     throw null;
 }
 /// <summary>
 /// 从 URL 获取参数。
 /// </summary>
 /// <param name="request">当前上下文的 <see cref="Microsoft.AspNetCore.Http.HttpRequest"/> 对象。</param>
 /// <param name="key">参数名。</param>
 /// <returns>参数值。</returns>
 private string GetUrlParameter(Microsoft.AspNetCore.Http.HttpRequest request, string key)
 {
     return(request.Query[key]);
 }
Exemplo n.º 23
0
        public KeyData GetPublicKey(Microsoft.AspNetCore.Http.HttpRequest request, string keyName)
        {
            string keyUid = "";

            _logger.LogInformation("get public key : " + keyName);
            keyName.ThrowIfNull(nameof(keyName));

            //get the UID of the key by searching in list keys
            JArray listKeys = ListKeys(request);

            foreach (JObject item in listKeys)
            {
                string itemKeyName = item.GetValue("id").ToString();
                if (itemKeyName == keyName)
                {
                    keyUid = item.GetValue("uid").ToString();
                }
            }

            string websiteHostName = System.Environment.GetEnvironmentVariable("UKC_SERVER_IP");
            string partition       = System.Environment.GetEnvironmentVariable("UKC_PARTITION");

            HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("https://" + websiteHostName + "/api/v1/keys/" + keyUid + "?partitionId=" + partition);

            request2.Method          = "GET";
            request2.KeepAlive       = true;
            request2.PreAuthenticate = true;

            request2.Headers.Add("Authorization", getToken(request));
            request2.Accept = "application/json";

            request2.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();

            string myResponse2 = "";

            using (System.IO.StreamReader sr = new System.IO.StreamReader(response2.GetResponseStream()))
            {
                myResponse2 = sr.ReadToEnd();
            }
            _logger.LogInformation("UKC response to getKey : " + myResponse2);

            JObject json = JObject.Parse(myResponse2);

            if (json.SelectToken("pkInfo.rsa.publicExponent") == null)
            {
                throw new System.ArgumentException("key " + keyName + " not found");
            }
            string publicExponent          = (string)json.SelectToken("pkInfo.rsa.publicExponent");
            string modulus                 = (string)json.SelectToken("pkInfo.rsa.modulus");
            string hexstr                  = modulus.Replace(":", "");
            string hexstrWithoutPrefixZero = hexstr.Substring(2, hexstr.Length - 2);
            string nStrBase64              = HexString2B64String(hexstrWithoutPrefixZero);


            //string nStrBase64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(modulus));

            // string nStrBase64 = "quZmxXahDC8x1tlbWw2+UV5jbZeCmQMzru3VftfIaxLvJQ8ft0fuaQo5LlPxtzxXNuPe3Ew55Qgxx0dLf24zwWA3cfnfUhxuNnTWaSGgrT18TKH8hD0wJ/d6QNSDmtSdnZyinp+XHixe0ifn+MydgtKjYp0UKBIMVS7e8GIwJPK48SFqWxmmGIxTW5+sMLosAJ28Co/00+vqPolXHX7uDnNfkoYfWfAgkdWIfK4ScKfu/1JmMxQTr4MFBLv1SmusR3ypyIp/mLL+MYPevYmqVFmCHK+yjNvAIPpissZ+tlzcpx8hqzdb2uDrTd9DkWa0OWGFGKv1qsoySfiZtuEUHw==";
            var publicKey = new PublicKey(nStrBase64, 65537);

            websiteHostName     = System.Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");
            publicKey.KeyId     = "https://" + websiteHostName + "/" + keyName + "/" + keyUid;
            publicKey.KeyType   = "RSA";
            publicKey.Algorithm = "RS256";

            return(new KeyData(publicKey));
        }
Exemplo n.º 24
0
 public static string GetDisplayUrl(this Microsoft.AspNetCore.Http.HttpRequest request) => throw null;
Exemplo n.º 25
0
 public ActionResult <List <Models.Widgets.IWidget> > GetAll()
 {
     Microsoft.AspNetCore.Http.HttpRequest       request = Request;
     Microsoft.AspNetCore.Http.IHeaderDictionary header  = request.Headers;
     return(widgets.GetAll().ToList());
 }
Exemplo n.º 26
0
 public static string GetEncodedPathAndQuery(this Microsoft.AspNetCore.Http.HttpRequest request) => throw null;
 public static string GetEncodedUrl(this Microsoft.AspNetCore.Http.HttpRequest request)
 {
     throw null;
 }
Exemplo n.º 28
0
 public static bool HasJsonContentType(this Microsoft.AspNetCore.Http.HttpRequest request) => throw null;
Exemplo n.º 29
0
        private void AddPreviousNextPageLinks(Microsoft.AspNetCore.Http.HttpRequest request, int pageSize)
        {
            if (this.TotalCount != 0 && pageSize > 0)
            {
                StringBuilder url      = new StringBuilder();
                string        protocol = request.Headers["X-Forwarded-Proto"];
                if (string.IsNullOrEmpty(protocol))
                {
                    url.Append(request.Scheme);
                }
                else
                {
                    url.Append(protocol);
                }
                url.Append("://");
                url.Append(request.Host);

                if (!string.IsNullOrEmpty(request.PathBase))
                {
                    url.Append("/");
                    url.Append(request.PathBase);
                }

                if (!string.IsNullOrEmpty(request.Path))
                {
                    url.Append(request.Path);
                }

                url.Append("?");
                int  startLength     = url.Length;
                bool addedPageSize   = false;
                bool addedStartIndex = false;
                int  count           = 0;
                foreach (string key in request.Query.Keys)
                {
                    if ((string.Compare(key, "referrerUrl", true) != 0) && (string.Compare(key, "session_token", true) != 0))
                    {
                        if (count > 0)
                        {
                            url.Append("&");
                        }
                        url.Append(key);
                        url.Append("=");
                        if (string.Compare(key, "pagesize", true) == 0)
                        {
                            url.Append(pageSize);
                            addedPageSize = true;
                        }
                        else if (string.Compare(key, "startindex", true) == 0)
                        {
                            url.Append("{0}");
                            addedStartIndex = true;
                        }
                        else
                        {
                            url.Append(WebUtility.UrlEncode(request.Query[key]));
                        }
                        count++;
                    }
                }
                if (!addedPageSize && pageSize != 20)
                {
                    if (url.Length > startLength)
                    {
                        url.Append("&");
                    }
                    url.Append("pageSize=");
                    url.Append(pageSize);
                }
                if (!addedStartIndex)
                {
                    if (url.Length > startLength)
                    {
                        url.Append("&");
                    }
                    url.Append("startIndex={0}");
                }
                if (this.StartIndex > 0)
                {
                    if (this.Links == null)
                    {
                        this.Links = new List <Link>();
                    }
                    this.Links.Add(new Link
                    {
                        rel  = "first",
                        href = string.Format(url.ToString(), 0)
                    });
                    this.Links.Add(new Link
                    {
                        rel  = "prev",
                        href = string.Format(url.ToString(), Math.Max(0, this.StartIndex - pageSize))
                    });
                }
                if (this.TotalCount < 0)
                {
                    if (Math.Abs(this.TotalCount) > pageSize)
                    {
                        if (this.Links == null)
                        {
                            this.Links = new List <Link>();
                        }
                        this.Links.Add(new Link
                        {
                            rel  = "next",
                            href = string.Format(url.ToString(), (this.StartIndex + this.ItemsCount))
                        });
                    }
                }
                else
                {
                    if ((this.StartIndex + this.ItemsCount) < this.TotalCount)
                    {
                        if (this.Links == null)
                        {
                            this.Links = new List <Link>();
                        }
                        this.Links.Add(new Link
                        {
                            rel  = "next",
                            href = string.Format(url.ToString(), (this.StartIndex + this.ItemsCount))
                        });
                        this.Links.Add(new Link
                        {
                            rel  = "last",
                            href = string.Format(url.ToString(), Math.Max(0, this.TotalCount - pageSize))
                        });
                    }
                }
            }
        }
Exemplo n.º 30
0
        internal static byte[] PerformMutations(string photoUrl, string extension, IEnumerable <MutationAction> actions, Microsoft.AspNetCore.Http.HttpRequest request, IMutationActionFactorySelector mutationActionFactorySelector)
        {
            byte[] fileBytes;
            using (WebClient webClient = new WebClient())
            {
                if (photoUrl.StartsWith("~"))
                {
                    photoUrl = $"{request.Scheme}://{request.Host}{photoUrl.TrimStart('~')}";
                }

                byte[] data = webClient.DownloadData(photoUrl);

                using (MemoryStream mem = new MemoryStream(data))
                {
                    MemoryStream ms = new MemoryStream();
                    using (Image <Rgba32> image = Image.Load <Rgba32>(mem))
                    {
                        foreach (var action in actions)
                        {
                            mutationActionFactorySelector.GetMutationActionFactory(action).GetMutationAction().Mutate(image);
                        }

                        image.Save(ms, ResolveImageEncoder(extension));
                    }
                    fileBytes = ms.ToArray();
                    ms.Close();
                }
            }
            return(fileBytes);
        }