映射到ASP.Net 4中的wwwroot?

Gra*_*ham 7 asp.net asp.net-mvc asp.net-web-api

有没有一种简单的方法可以在包含我所有客户端内容的ASP.Net v4 Web API中添加子目录?我今天已经阅读了很多关于虚拟路径和路由的文章,但没有任何内容能够完整地描述这种情况.

例如,我想将我的图像存储在wwwroot下,以便当应用程序收到此请求时:

HTTP://myapp/img/logo.png

它获取wwwroot\img\logo.png来处理请求.显然,我不想单独映射每个文件或文件夹.

将有一个Web API restful Web服务,它将由WebApiConfig.cs中的常规路由功能处理.

(注意:我问这个是因为我计划将我们的应用程序迁移到ASP.Net v5,当它是GA时,这会使客户端代码变得微不足道)

Ben*_*ger 10

您可以使用Microsoft.Owin.FileSystem和Microsoft.Owin.StaticFiles NuGet包来实现您的需求.

首先添加两个NuGet包.

然后将此代码添加到您的Startup类:

    public void Configuration(IAppBuilder app)
    {
        // here your other startup code like app.UseWebApi(config); etc.

        ConfigureStaticFiles(app);
    }

    private void ConfigureStaticFiles(IAppBuilder app)
    {
        string root = AppDomain.CurrentDomain.BaseDirectory;
        string wwwroot = Path.Combine(root, "wwwroot");

        var fileServerOptions = new FileServerOptions()
        {
            EnableDefaultFiles = true,
            EnableDirectoryBrowsing = false,
            RequestPath = new PathString(string.Empty),
            FileSystem = new PhysicalFileSystem(wwwroot)
        };

        fileServerOptions.StaticFileOptions.ServeUnknownFileTypes = true;
        app.UseFileServer(fileServerOptions);
    }
Run Code Online (Sandbox Code Playgroud)

此外,您必须确保在Web.config文件中注册了处理程序.它应该如下所示:

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <add name="Owin" verb="" path="*" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler, Microsoft.Owin.Host.SystemWeb"/>
    </handlers>
  </system.webServer>
Run Code Online (Sandbox Code Playgroud)

然后,您的"wwwroot"文件夹中的每个文件都将自动访问.

例如,你的wwwroot/img/logo.png文件可以通过http://yourdomain.com/img/logo.png访问,就像你想要的那样:)

如果您在构建事件中使用npm/gulp/grunt生成wwwroot文件夹的内容,那么您可能还需要编辑csproj文件并添加此ItemGroup:

  <ItemGroup>
    <Content Include="wwwroot\**\*" />
  </ItemGroup>
Run Code Online (Sandbox Code Playgroud)


Jul*_*lla 3

将 img 文件夹添加到应用程序的根目录中。此外,您还必须在项目或应用程序中包含图像

在此输入图像描述