ASP.Net Core RC1:System.ArgumentException:路径中的非法字符

时间:2016-01-15 18:47:03

标签: asp.net-core asp.net-core-mvc

Please note: As the answer shows this problem is specific for ASP.Net Core Release Candidate 1.

在ASP.Net Core / MVC 6中访问URL http://localhost:58000/Admin/RebuildIndex/AspNetUserRoles/PK_IdentityUserRole%3Cstring%3E

给出了这个错误:

  

System.ArgumentException:路径中的非法字符。
  在System.IO.Path.CheckInvalidPathChars(String path,Boolean   checkAdditional)
  在System.IO.Path.GetExtension(String path)
  在Microsoft.AspNet.StaticFiles.FileExtensionContentTypeProvider.TryGetContentType(String subpath,String& contentType)
  在Microsoft.AspNet.StaticFiles.StaticFileContext.LookupContentType()
  在Microsoft.AspNet.StaticFiles.StaticFileMiddleware.Invoke(HttpContext   上下文)
  在Microsoft.AspNet.IISPlatformHandler.IISPlatformHandlerMiddleware.d__8.MoveNext()

这是由于<和> URL中的字符。如果我访问其他页面,例如http://localhost:58000/Admin/RebuildIndex/AspNetRoles/RoleNameIndex,那么它可以正常工作。

我的路线是:

app.UseMvc(routes =>
{
    // Area route
    routes.MapRoute(name: "areaRoute",
        template: "{area:exists}/{controller}/{action}",
        defaults: new { controller = "Home", action = "Index" });

    // Default route
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

我正在访问的控制器如下所示:

[Route("Admin")]
public class AdminController : Controller
{
    [Route("RebuildIndex/{tableName}/{indexName}")]
    [HttpGet]
    [Authorize(Roles="Admin")]
    public async Task<IActionResult> RebuildIndex(string tableName, string indexName)
    {
        // ...
    }
}

在ASP.Net的早期版本中,我们使用Web.Config中的httpRuntime标记来放松“我们从客户端检测到一个潜在危险的Request.Path值(&amp;)”错误。所以我在web.config中尝试了以下(以及它的一些变体)但没有成功:

  <system.web>
    <httpRuntime requestValidationMode="2.0" relaxedUrlToFileSystemMapping="true" requestPathInvalidCharacters="" />
  </system.web>

然而,查看错误消息时,此错误似乎是因为请求是作为静态文件处理的,而不是提供给MVC控制器。

如何在ASP.Net Core中解决这个问题?如果只允许特定路径的解决方案,这将是一件好事。

1 个答案:

答案 0 :(得分:1)

这是 RC2 已经记录并修复的问题(根据the roadmap,应在2016年2月发布)。

  • 检查AspNet.StaticFiles repo。{/ li>的issue 82

如果您想知道,可以查看FileExtensionContentTypeProvider课程的最新版本。您会看到TryGetExtension不再使用System.IO.Path.GetExtension(他们甚至添加了您会发现非常有趣的评论!):

public bool TryGetContentType(string subpath, out string contentType)
{
    string extension = GetExtension(subpath);
    if (extension == null)
    {
        contentType = null;
        return false;
    }
    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);
}

所以我猜你可以等待RC2被释放或使用StaticFiles repo的本地克隆。