示例#1
0
        /// <summary>
        /// ProcessFormFileAsync
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="permittedFileSuffixes"></param>
        /// <param name="sizeLimit"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task <byte[]> ProcessFormFileAsync(IFormFile?formFile, string[] permittedFileSuffixes, long sizeLimit)
        {
            // Check the file length. This check doesn't catch files that only have
            // a BOM as their content.
            if (formFile == null || formFile.Length == 0 || permittedFileSuffixes.IsNullOrEmpty())
            {
                throw ApiExceptions.ApiUploadEmptyFile();
            }

            if (formFile.Length > sizeLimit)
            {
                throw ApiExceptions.ApiUploadOverSize();
            }

            try
            {
                using MemoryStream memoryStream = new MemoryStream();

                await formFile.CopyToAsync(memoryStream).ConfigureAwait(false);

                // Check the content length in case the file's only
                // content was a BOM and the content is actually
                // empty after removing the BOM.
                if (memoryStream.Length == 0)
                {
                    throw ApiExceptions.ApiUploadEmptyFile();
                }

                if (!IsValidFileExtensionAndSignature(
                        formFile.FileName, memoryStream, permittedFileSuffixes))
                {
                    throw ApiExceptions.ApiUploadWrongType();
                }
                else
                {
                    return(memoryStream.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw ApiExceptions.ServerUnkownError(fileName: formFile.FileName, innerException: ex);
            }
        }
        /// <exception cref="ApiException"></exception>
        public static async Task ThrowIfNotSuccessedAsync(HttpResponseMessage responseMessage)
        {
            if (responseMessage.IsSuccessStatusCode)
            {
                return;
            }

            //TODO: 可以处理404等ProblemDetails的返回
            ErrorCode?errorCode = await responseMessage.DeSerializeJsonAsync <ErrorCode>().ConfigureAwait(false);

            responseMessage.Dispose();

            if (errorCode == null)
            {
                throw ApiExceptions.ServerUnkownError(response: responseMessage);
            }
            else
            {
                throw ApiExceptions.ServerReturnError(errorCode);
            }
        }