diff --git a/src/Microsoft.AspNet.StaticFiles/FileExtensionContentTypeProvider.cs b/src/Microsoft.AspNet.StaticFiles/FileExtensionContentTypeProvider.cs index 950bceafa1..a4c806bf4e 100644 --- a/src/Microsoft.AspNet.StaticFiles/FileExtensionContentTypeProvider.cs +++ b/src/Microsoft.AspNet.StaticFiles/FileExtensionContentTypeProvider.cs @@ -426,7 +426,7 @@ namespace Microsoft.AspNet.StaticFiles /// True if MIME type could be determined public bool TryGetContentType(string subpath, out string contentType) { - string extension = Path.GetExtension(subpath); + string extension = GetExtension(subpath); if (extension == null) { contentType = null; @@ -434,5 +434,25 @@ namespace Microsoft.AspNet.StaticFiles } return Mappings.TryGetValue(extension, out contentType); } + + private static string GetExtension(string path) + { + // Don't use Path.GetExtension as that may throw an exception if there are + // invalid characters in the path. Invalid characters should be handled + // by the FileProviders + + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + + int index = path.LastIndexOf('.'); + if (index < 0) + { + return null; + } + + return path.Substring(index); + } } } \ No newline at end of file diff --git a/test/Microsoft.AspNet.StaticFiles.Tests/DefaultContentTypeProviderTests.cs b/test/Microsoft.AspNet.StaticFiles.Tests/DefaultContentTypeProviderTests.cs index 64d1bf76cc..b56ec0ba29 100644 --- a/test/Microsoft.AspNet.StaticFiles.Tests/DefaultContentTypeProviderTests.cs +++ b/test/Microsoft.AspNet.StaticFiles.Tests/DefaultContentTypeProviderTests.cs @@ -62,5 +62,13 @@ namespace Microsoft.AspNet.StaticFiles Assert.True(provider.TryGetContentType(@"\second.css\example.txt", out contentType)); Assert.Equal("text/plain", contentType); } + + [Fact] + public void InvalidCharactersAreIgnored() + { + var provider = new FileExtensionContentTypeProvider(); + string contentType; + Assert.True(provider.TryGetContentType($"{new string(System.IO.Path.GetInvalidPathChars())}.txt", out contentType)); + } } }