Exemplo n.º 1
0
 public ActionResult Get(string filename)
 {
     FileEntity fileEntity = GetFileInfo(filename);
     string fileFullPath = System.IO.Path.Combine(@"C:\", fileEntity.file_path, filename);
     if (fileEntity == null)
         return NotFound();
     FileStream fileStream = System.IO.File.Open(fileFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     long startByteIndex = 0;
     long endByteIndex = fileEntity.file_length-1;
     var reqTypedHeader = Request.GetTypedHeaders();
     if (reqTypedHeader.Range!=null && reqTypedHeader.Range.Ranges.Count>0)
     {
         //断点续传处理,多range情景没有处理
         startByteIndex = reqTypedHeader.Range.Ranges.First().From ?? 0;
         endByteIndex = reqTypedHeader.Range.Ranges.First().To ?? fileEntity.file_length - 1;
         Response.StatusCode = StatusCodes.Status206PartialContent;
         var contentRange = new ContentRangeHeaderValue(startByteIndex, endByteIndex);
         Response.Headers[HeaderNames.ContentRange] = contentRange.ToString();
     }
     Response.ContentType = fileEntity.file_mimetype;
     var contentDisposition = new ContentDispositionHeaderValue("attachment");
     contentDisposition.SetHttpFileName(fileEntity.file_name);
     Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     Response.ContentLength = fileStream.Length;
     Response.Headers[HeaderNames.AcceptRanges] = "bytes";
     return new FileStreamResult(fileStream,fileEntity.file_mimetype);
 }
Exemplo n.º 2
0
        public static void SetFileHeaders(this IHttpResponse response,
                                          string fileName, string contentType, bool?inline)
        {
            if (contentType.HasBlackSpace())
            {
                response.SetContentType(contentType);
            }

            if (inline.HasValue || fileName.HasBlackSpace())
            {
                var dispositionType = GetDispositiontype();
                var dispHeader      = new ContentDispositionHeaderValue(dispositionType)
                {
                    FileName = fileName,
                };
                var dispositionHeaderValue = dispHeader.ToString();
                response.SetHeader("Content-Disposition", dispositionHeaderValue);

                string GetDispositiontype()
                {
                    if (inline.HasValue)
                    {
                        if (!inline.Value)
                        {
                            return("attachment");
                        }
                    }

                    return("inline");
                }
            }
        }
Exemplo n.º 3
0
        /// <inheritdoc />
        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
            var logger = loggerFactory.CreateLogger<FileResult>();

            var response = context.HttpContext.Response;
            response.ContentType = ContentType.ToString();

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                var contentDisposition = new ContentDispositionHeaderValue("attachment");
                contentDisposition.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }

            logger.FileResultExecuting(FileDownloadName);
            return WriteFileAsync(response);
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public override Task ExecuteResultAsync([NotNull] ActionContext context)
        {
            var response = context.HttpContext.Response;

            if (ContentType != null)
            {
                response.ContentType = ContentType;
            }

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                var cd = new ContentDispositionHeaderValue("attachment");
                cd.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers.Set(HeaderNames.ContentDisposition, cd.ToString());
            }

            // We aren't flowing the cancellation token appropriately, see
            // https://github.com/aspnet/Mvc/issues/743 for details.
            return WriteFileAsync(response, CancellationToken.None);
        }
 public static bool HasFileContentDisposition(Microsoft.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition)
 {
     return(contentDisposition != null &&
            contentDisposition.DispositionType.Equals("form-data") &&
            (!string.IsNullOrEmpty(contentDisposition.FileName.ToString()) ||
             !string.IsNullOrEmpty(contentDisposition.FileNameStar.ToString())));
 }
Exemplo n.º 6
0
 public static bool HasFormDataContentDisposition(Microsoft.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition)
 {
     // Content-Disposition: form-data; name="key";
     return(contentDisposition != null &&
            contentDisposition.DispositionType.Equals("form-data") &&
            string.IsNullOrEmpty(contentDisposition.FileName.ToString()) &&
            string.IsNullOrEmpty(contentDisposition.FileNameStar.ToString()));
 }
        public void ContentDisposition_SetAndGetContentDisposition_MatchExpectations()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");
            Assert.Equal("inline", contentDisposition.DispositionType);

            contentDisposition.DispositionType = "attachment";
            Assert.Equal("attachment", contentDisposition.DispositionType);
        }
Exemplo n.º 8
0
 public static bool HasFormDataContentDisposition(Microsoft.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition)
 {
     // Content-Disposition: form-data; name="key";
     return(contentDisposition != null &&
            contentDisposition.DispositionType.Equals("form-data") &&
            string.IsNullOrEmpty(contentDisposition.FileName.Value) &&  // For .NET Core <2.0 remove ".Value"
            string.IsNullOrEmpty(contentDisposition.FileNameStar.Value));    // For .NET Core <2.0 remove ".Value"
 }
Exemplo n.º 9
0
 public static bool HasFileContentDisposition(Microsoft.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition)
 {
     // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg"
     return(contentDisposition != null &&
            contentDisposition.DispositionType.Equals("form-data") &&
            (!string.IsNullOrEmpty(contentDisposition.FileName.Value) ||  // For .NET Core <2.0 remove ".Value"
             !string.IsNullOrEmpty(contentDisposition.FileNameStar.Value)));       // For .NET Core <2.0 remove ".Value"
 }
Exemplo n.º 10
0
 private static void SetContentDispositionHeader(HttpContext httpContext, string fileName)
 {
     if (!string.IsNullOrEmpty(fileName))
     {
         var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
         contentDisposition.SetHttpFileName(fileName);
         httpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     }
 }
Exemplo n.º 11
0
 private void SetContentDispositionHeader(ActionContext context, FileResult result)
 {
     if (!string.IsNullOrEmpty(result.FileDownloadName))
     {
         var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue(ContentDispositionHeader.ToString());
         contentDisposition.SetHttpFileName(result.FileDownloadName);
         context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     }
 }
 public void Ctor_ContentDispositionValidFormat_SuccessfullyCreated()
 {
     var contentDisposition = new ContentDispositionHeaderValue("inline");
     Assert.Equal("inline", contentDisposition.DispositionType);
     Assert.Equal(0, contentDisposition.Parameters.Count);
     Assert.Null(contentDisposition.Name);
     Assert.Null(contentDisposition.FileName);
     Assert.Null(contentDisposition.CreationDate);
     Assert.Null(contentDisposition.ModificationDate);
     Assert.Null(contentDisposition.ReadDate);
     Assert.Null(contentDisposition.Size);
 }
Exemplo n.º 13
0
        public static void WriteExcelToResponse(this IWorkbook book, HttpContext httpContext, string templateName)
        {
            var response = httpContext.Response;

            response.ContentType = "application/vnd.ms-excel";
            if (!string.IsNullOrEmpty(templateName))
            {
                var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                contentDisposition.SetHttpFileName(templateName);
                response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }
            book.Write(response.Body);
        }
        public void Name_SetNameAndValidateObject_ParametersEntryForNameAdded()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");
            contentDisposition.Name = "myname";
            Assert.Equal("myname", contentDisposition.Name);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("name", contentDisposition.Parameters.First().Name);

            contentDisposition.Name = null;
            Assert.Null(contentDisposition.Name);
            Assert.Equal(0, contentDisposition.Parameters.Count);
            contentDisposition.Name = null; // It's OK to set it again to null; no exception.
        }
Exemplo n.º 15
0
        public static Task <HttpResponseData> CreateFileContentResponseAsync(this HttpRequestData request, byte[] content, string contentType, string filename)
        {
            var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(filename);

            var httpResponse = request.CreateResponse(HttpStatusCode.OK);

            httpResponse.Headers.Add("Content-Type", contentType);
            httpResponse.Headers.Add("Content-Length", content.Length.ToString());
            httpResponse.Headers.Add(HeaderNames.ContentDisposition, contentDisposition.ToString());
            httpResponse.WriteBytes(content);

            return(Task.FromResult(httpResponse));
        }
Exemplo n.º 16
0
 /// <summary>
 /// Makes the zip of the app to download
 /// </summary>
 /// <param name="endpoints">The endpoints.</param>
 /// <param name="app">App builder.</param>
 public static void MapZip(this IEndpointRouteBuilder endpoints, IApplicationBuilder app)
 {
     //see more at
     //https://andrewlock.net/converting-a-terminal-middleware-to-endpoint-routing-in-aspnetcore-3/
     endpoints.Map("/zip", async context =>
     {
         var response         = context.Response;
         var name             = Assembly.GetEntryAssembly().GetName().Name + ".zip";
         response.ContentType = "application/octet-stream";
         var b = GetZip(app.ApplicationServices.GetService <IWebHostEnvironment>());
         //https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs
         var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
         contentDisposition.SetHttpFileName(name);
         response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
         await response.Body.WriteAsync(b);
     });
 }
Exemplo n.º 17
0
        public async Task <IActionResult> DownloadAttachment(string id)
        {
            var docField = await _queryService.GetDocumentFieldById(id);

            if (!String.IsNullOrEmpty(docField.FilePath))
            {
                var path = docField.FilePath;

                var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = docField.Value
                };
                Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();

                var response = new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream");
                return(response);
            }
            return(Json("File not found"));
        }
 private void CheckValidParse(string input, ContentDispositionHeaderValue expectedResult)
 {
     var result = ContentDispositionHeaderValue.Parse(input);
     Assert.Equal(expectedResult, result);
 }
        public void FileNameStar_UnknownOrBadEncoding_PropertyFails()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            var fileNameStar = new NameValueHeaderValue("FILENAME*", "utf-99'lang'File%CZName.bat");
            contentDisposition.Parameters.Add(fileNameStar);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);
            Assert.Equal("utf-99'lang'File%CZName.bat", contentDisposition.Parameters.First().Value);
            Assert.Null(contentDisposition.FileNameStar); // Decode failure

            contentDisposition.FileNameStar = "new_name";
            Assert.Equal("new_name", contentDisposition.FileNameStar);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);

            contentDisposition.Parameters.Remove(fileNameStar);
            Assert.Null(contentDisposition.FileNameStar);
        }
        private static int GetDispositionTypeLength(string input, int startIndex, out ContentDispositionHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

            if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return 0;
            }

            // Caller must remove leading whitespaces. If not, we'll return 0.
            string dispositionType = null;
            var dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out dispositionType);

            if (dispositionTypeLength == 0)
            {
                return 0;
            }

            var current = startIndex + dispositionTypeLength;
            current = current + HttpRuleParser.GetWhitespaceLength(input, current);
            var contentDispositionHeader = new ContentDispositionHeaderValue();
            contentDispositionHeader._dispositionType = dispositionType;

            // If we're not done and we have a parameter delimiter, then we have a list of parameters.
            if ((current < input.Length) && (input[current] == ';'))
            {
                current++; // skip delimiter.
                int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
                    contentDispositionHeader.Parameters);

                parsedValue = contentDispositionHeader;
                return current + parameterLength - startIndex;
            }

            // We have a ContentDisposition header without parameters.
            parsedValue = contentDispositionHeader;
            return current - startIndex;
        }
Exemplo n.º 21
0
 [InlineData(@"attachment; filename==?utf-8?B?Zm9vLeQuaHRtbA==?=")]  // @"Uses RFC 2047 style encoded word. ""="" is invalid inside the token production, so this is invalid.", false) },
 public void ContentDispositionHeaderValue_ParseInvalid_Throws(string input)
 {
     Assert.Throws <FormatException>(() => ContentDispositionHeaderValue.Parse(input));
 }
Exemplo n.º 22
0
        public static bool TryParse(StringSegment input, out ContentDispositionHeaderValue parsedValue)
        {
            var index = 0;

            return(Parser.TryParseValue(input, ref index, out parsedValue));
        }
Exemplo n.º 23
0
        private void CheckValidParse(string input, ContentDispositionHeaderValue expectedResult)
        {
            var result = ContentDispositionHeaderValue.Parse(input);

            Assert.Equal(expectedResult, result);
        }
        public void FileName_NeedsEncoding_EncodedAndDecodedCorrectly()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            contentDisposition.FileName = "FileÃName.bat";
            Assert.Equal("FileÃName.bat", contentDisposition.FileName);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("filename", contentDisposition.Parameters.First().Name);
            Assert.Equal("\"=?utf-8?B?RmlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.Parameters.First().Value);

            contentDisposition.Parameters.Remove(contentDisposition.Parameters.First());
            Assert.Null(contentDisposition.FileName);
        }
 public static bool TryParse(string input, out ContentDispositionHeaderValue parsedValue)
 {
     var index = 0;
     return Parser.TryParseValue(input, ref index, out parsedValue);
 }
Exemplo n.º 26
0
 private bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition)
 {
     // Content-Disposition: form-data; name="key";
     return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data")
         && string.IsNullOrEmpty(contentDisposition.FileName) && string.IsNullOrEmpty(contentDisposition.FileNameStar);
 }
        public void Size_InvalidSizes_PropertyFails()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            var sizeParameter = new NameValueHeaderValue("SIZE", "-279172874239");
            contentDisposition.Parameters.Add(sizeParameter);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);
            Assert.Null(contentDisposition.Size);

            // Negatives not allowed
            Assert.Throws<ArgumentOutOfRangeException>(() => contentDisposition.Size = -279172874240);
            Assert.Null(contentDisposition.Size);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);

            contentDisposition.Parameters.Remove(sizeParameter);
            Assert.Null(contentDisposition.Size);
        }
        public void Size_AddSizeParameterThenUseProperty_ParametersEntryIsOverwritten()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            var sizeParameter = new NameValueHeaderValue("SIZE", "279172874239");
            contentDisposition.Parameters.Add(sizeParameter);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);
            Assert.Equal(279172874239, contentDisposition.Size);

            contentDisposition.Size = 279172874240;
            Assert.Equal(279172874240, contentDisposition.Size);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("SIZE", contentDisposition.Parameters.First().Name);

            contentDisposition.Parameters.Remove(sizeParameter);
            Assert.Null(contentDisposition.Size);
        }
        public void Dates_InvalidDates_PropertyFails()
        {
            string invalidDateString = "\"Tue, 15 Nov 94 08:12 GMT\"";

            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            var dateParameter = new NameValueHeaderValue("read-DATE", invalidDateString);
            contentDisposition.Parameters.Add(dateParameter);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("read-DATE", contentDisposition.Parameters.First().Name);

            Assert.Null(contentDisposition.ReadDate);

            contentDisposition.ReadDate = null;
            Assert.Null(contentDisposition.ReadDate);
            Assert.Equal(0, contentDisposition.Parameters.Count);
        }
        public void Dates_AddDateParameterThenUseProperty_ParametersEntryIsOverwritten()
        {
            string validDateString = "\"Tue, 15 Nov 1994 08:12:31 GMT\"";
            DateTimeOffset validDate = DateTimeOffset.Parse("Tue, 15 Nov 1994 08:12:31 GMT");

            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            var dateParameter = new NameValueHeaderValue("Creation-DATE", validDateString);
            contentDisposition.Parameters.Add(dateParameter);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("Creation-DATE", contentDisposition.Parameters.First().Name);

            Assert.Equal(validDate, contentDisposition.CreationDate);

            var newDate = validDate.AddSeconds(1);
            contentDisposition.CreationDate = newDate;
            Assert.Equal(newDate, contentDisposition.CreationDate);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("Creation-DATE", contentDisposition.Parameters.First().Name);
            Assert.Equal("\"Tue, 15 Nov 1994 08:12:32 GMT\"", contentDisposition.Parameters.First().Value);

            contentDisposition.Parameters.Remove(dateParameter);
            Assert.Null(contentDisposition.CreationDate);
        }
 private void CheckValidTryParse(string input, ContentDispositionHeaderValue expectedResult)
 {
     ContentDispositionHeaderValue result = null;
     Assert.True(ContentDispositionHeaderValue.TryParse(input, out result), input);
     Assert.Equal(expectedResult, result);
 }
Exemplo n.º 32
0
 private void CheckInvalidParse(string input)
 {
     Assert.Throws <FormatException>(() => ContentDispositionHeaderValue.Parse(input));
 }
        public void Equals_UseContentDispositionWithAndWithoutParameters_EqualOrNotEqualNoExceptions()
        {
            var contentDisposition1 = new ContentDispositionHeaderValue("inline");
            var contentDisposition2 = new ContentDispositionHeaderValue("inline");
            contentDisposition2.Name = "myName";
            var contentDisposition3 = new ContentDispositionHeaderValue("inline");
            contentDisposition3.Parameters.Add(new NameValueHeaderValue("name", "value"));
            var contentDisposition4 = new ContentDispositionHeaderValue("INLINE");
            var contentDisposition5 = new ContentDispositionHeaderValue("INLINE");
            contentDisposition5.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME"));
            var contentDisposition6 = new ContentDispositionHeaderValue("INLINE");
            contentDisposition6.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME"));
            contentDisposition6.Parameters.Add(new NameValueHeaderValue("custom", "value"));
            var contentDisposition7 = new ContentDispositionHeaderValue("attachment");

            Assert.False(contentDisposition1.Equals(contentDisposition2), "No params vs. name.");
            Assert.False(contentDisposition2.Equals(contentDisposition1), "name vs. no params.");
            Assert.False(contentDisposition1.Equals(null), "No params vs. <null>.");
            Assert.False(contentDisposition1.Equals(contentDisposition3), "No params vs. custom param.");
            Assert.False(contentDisposition2.Equals(contentDisposition3), "name vs. custom param.");
            Assert.True(contentDisposition1.Equals(contentDisposition4), "Different casing.");
            Assert.True(contentDisposition2.Equals(contentDisposition5), "Different casing in name.");
            Assert.False(contentDisposition5.Equals(contentDisposition6), "name vs. custom param.");
            Assert.False(contentDisposition1.Equals(contentDisposition7), "inline vs. text/other.");
        }
        public void Name_AddNameParameterThenUseProperty_ParametersEntryIsOverwritten()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            NameValueHeaderValue name = new NameValueHeaderValue("NAME", "old_name");
            contentDisposition.Parameters.Add(name);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("NAME", contentDisposition.Parameters.First().Name);

            contentDisposition.Name = "new_name";
            Assert.Equal("new_name", contentDisposition.Name);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("NAME", contentDisposition.Parameters.First().Name);

            contentDisposition.Parameters.Remove(name);
            Assert.Null(contentDisposition.Name);
        }
        public void Parse_SetOfValidValueStrings_ParsedCorrectly()
        {
            var expected = new ContentDispositionHeaderValue("inline");
            CheckValidParse("\r\n inline  ", expected);
            CheckValidParse("inline", expected);

            // We don't have to test all possible input strings, since most of the pieces are handled by other parsers.
            // The purpose of this test is to verify that these other parsers are combined correctly to build a
            // Content-Disposition parser.
            expected.Name = "myName";
            CheckValidParse("\r\n inline  ;  name =   myName ", expected);
            CheckValidParse("  inline;name=myName", expected);

            expected.Name = null;
            expected.DispositionType = "attachment";
            expected.FileName = "foo-ae.html";
            expected.Parameters.Add(new NameValueHeaderValue("filename*", "UTF-8''foo-%c3%a4.html"));
            CheckValidParse(@"attachment; filename*=UTF-8''foo-%c3%a4.html; filename=foo-ae.html", expected);
        }
        public void FileNameStar_AddNameParameterThenUseProperty_ParametersEntryIsOverwritten()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            var fileNameStar = new NameValueHeaderValue("FILENAME*", "old_name");
            contentDisposition.Parameters.Add(fileNameStar);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);
            Assert.Null(contentDisposition.FileNameStar); // Decode failure

            contentDisposition.FileNameStar = "new_name";
            Assert.Equal("new_name", contentDisposition.FileNameStar);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name);
            Assert.Equal("UTF-8\'\'new_name", contentDisposition.Parameters.First().Value);

            contentDisposition.Parameters.Remove(fileNameStar);
            Assert.Null(contentDisposition.FileNameStar);
        }
        public void FileName_UnknownOrBadEncoding_PropertyFails()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            // Note that uppercase letters are used. Comparison should happen case-insensitive.
            var fileName = new NameValueHeaderValue("FILENAME", "\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\"");
            contentDisposition.Parameters.Add(fileName);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name);
            Assert.Equal("\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.Parameters.First().Value);
            Assert.Equal("\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.FileName);

            contentDisposition.FileName = "new_name";
            Assert.Equal("new_name", contentDisposition.FileName);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name);

            contentDisposition.Parameters.Remove(fileName);
            Assert.Null(contentDisposition.FileName);
        }
Exemplo n.º 38
0
        private static int GetDispositionTypeLength(StringSegment input, int startIndex, out ContentDispositionHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

            if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return(0);
            }

            // Caller must remove leading whitespaces. If not, we'll return 0.
            var dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out var dispositionType);

            if (dispositionTypeLength == 0)
            {
                return(0);
            }

            var current = startIndex + dispositionTypeLength;

            current = current + HttpRuleParser.GetWhitespaceLength(input, current);
            var contentDispositionHeader = new ContentDispositionHeaderValue();

            contentDispositionHeader._dispositionType = dispositionType;

            // If we're not done and we have a parameter delimiter, then we have a list of parameters.
            if ((current < input.Length) && (input[current] == ';'))
            {
                current++; // skip delimiter.
                int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
                                                                                  contentDispositionHeader.Parameters);

                parsedValue = contentDispositionHeader;
                return(current + parameterLength - startIndex);
            }

            // We have a ContentDisposition header without parameters.
            parsedValue = contentDispositionHeader;
            return(current - startIndex);
        }
 public void ContentDispositionHeaderValue_ParseValid_Success(string input, ContentDispositionHeaderValue expected)
 {
     // System.Diagnostics.Debugger.Launch();
     var result = ContentDispositionHeaderValue.Parse(input);
     Assert.Equal(expected, result);
 }
Exemplo n.º 40
0
        public void Parameters_AddNull_Throw()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            Assert.Throws <ArgumentNullException>(() => contentDisposition.Parameters.Add(null));
        }
 public void Parameters_AddNull_Throw()
 {
     var contentDisposition = new ContentDispositionHeaderValue("inline");
     Assert.Throws<ArgumentNullException>(() => contentDisposition.Parameters.Add(null));
 }
Exemplo n.º 42
0
        public void GetHeaderValue_Produces_Correct_ContentDisposition(string input, string expectedOutput)
        {
            // Arrange & Act
            var cd = new ContentDispositionHeaderValue("attachment");
            cd.SetHttpFileName(input);
            var actual = cd.ToString();

            // Assert
            Assert.Equal(expectedOutput, actual);
        }
        public void FileNameStar_NeedsEncoding_EncodedAndDecodedCorrectly()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            contentDisposition.FileNameStar = "FileÃName.bat";
            Assert.Equal("FileÃName.bat", contentDisposition.FileNameStar);
            Assert.Equal(1, contentDisposition.Parameters.Count);
            Assert.Equal("filename*", contentDisposition.Parameters.First().Name);
            Assert.Equal("UTF-8\'\'File%C3%83Name.bat", contentDisposition.Parameters.First().Value);

            contentDisposition.Parameters.Remove(contentDisposition.Parameters.First());
            Assert.Null(contentDisposition.FileNameStar);
        }
        public void ToString_UseDifferentContentDispositions_AllSerializedCorrectly()
        {
            var contentDisposition = new ContentDispositionHeaderValue("inline");
            Assert.Equal("inline", contentDisposition.ToString());

            contentDisposition.Name = "myname";
            Assert.Equal("inline; name=myname", contentDisposition.ToString());

            contentDisposition.FileName = "my File Name";
            Assert.Equal("inline; name=myname; filename=\"my File Name\"", contentDisposition.ToString());

            contentDisposition.CreationDate = new DateTimeOffset(new DateTime(2011, 2, 15));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"", contentDisposition.ToString());

            contentDisposition.Parameters.Add(new NameValueHeaderValue("custom", "\"custom value\""));
            Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"",  contentDisposition.ToString());

            contentDisposition.Name = null;
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString());

            contentDisposition.FileNameStar = "File%Name";
            Assert.Equal("inline; filename=\"my File Name\"; creation-date="
                + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"; filename*=UTF-8\'\'File%25Name",
                contentDisposition.ToString());

            contentDisposition.FileName = null;
            Assert.Equal("inline; creation-date=\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\";"
                + " filename*=UTF-8\'\'File%25Name", contentDisposition.ToString());

            contentDisposition.CreationDate = null;
            Assert.Equal("inline; custom=\"custom value\"; filename*=UTF-8\'\'File%25Name",
                contentDisposition.ToString());
        }
        public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
        {
            var expected = new ContentDispositionHeaderValue("inline");
            CheckValidTryParse("\r\n inline  ", expected);
            CheckValidTryParse("inline", expected);

            // We don't have to test all possible input strings, since most of the pieces are handled by other parsers.
            // The purpose of this test is to verify that these other parsers are combined correctly to build a
            // Content-Disposition parser.
            expected.Name = "myName";
            CheckValidTryParse("\r\n inline  ;  name =   myName ", expected);
            CheckValidTryParse("  inline;name=myName", expected);
        }
Exemplo n.º 46
0
 private bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition)
 {
     // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg"
     return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data")
         && (!string.IsNullOrEmpty(contentDisposition.FileName) || !string.IsNullOrEmpty(contentDisposition.FileNameStar));
 }
        public void GetHashCode_UseContentDispositionWithAndWithoutParameters_SameOrDifferentHashCodes()
        {
            var contentDisposition1 = new ContentDispositionHeaderValue("inline");
            var contentDisposition2 = new ContentDispositionHeaderValue("inline");
            contentDisposition2.Name = "myname";
            var contentDisposition3 = new ContentDispositionHeaderValue("inline");
            contentDisposition3.Parameters.Add(new NameValueHeaderValue("name", "value"));
            var contentDisposition4 = new ContentDispositionHeaderValue("INLINE");
            var contentDisposition5 = new ContentDispositionHeaderValue("INLINE");
            contentDisposition5.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME"));

            Assert.NotEqual(contentDisposition1.GetHashCode(), contentDisposition2.GetHashCode());
            Assert.NotEqual(contentDisposition1.GetHashCode(), contentDisposition3.GetHashCode());
            Assert.NotEqual(contentDisposition2.GetHashCode(), contentDisposition3.GetHashCode());
            Assert.Equal(contentDisposition1.GetHashCode(), contentDisposition4.GetHashCode());
            Assert.Equal(contentDisposition2.GetHashCode(), contentDisposition5.GetHashCode());
        }