是否有一种简单的方法可以在 ASP.Net v4 Web API 中添加包含我的所有客户端内容的子目录?我今天读了很多有关虚拟路径和路由的文章,但没有任何文章能够完全描述这种情况。
例如,我想将图像存储在 wwwroot 下,因此当应用程序收到此请求时:
它获取 wwwroot\img\logo.png 来处理请求。显然,我不想单独映射每个文件或文件夹。
将有一个 Web API Restful Web 服务,该服务将由 WebApiConfig.cs 中的常规路由功能处理。
(注意:我问这个问题是因为我计划在 GA 发布时将我们的应用程序迁移到 ASP.Net v5,这将使移动客户端代码变得微不足道)
最佳答案
您可以使用 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);
}
此外,您还必须确保处理程序已在 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>
然后“wwwroot”文件夹中的每个文件都将自动可访问。
例如,您的 wwwroot/img/logo.png 文件可通过 http://yourdomain.com/img/logo.png 访问,就像你想要的那样:)
如果您在构建事件中使用 npm/gulp/grunt 生成 wwwroot 文件夹的内容,那么也许您还必须编辑 csproj 文件并添加此 ItemGroup:
<ItemGroup>
<Content Include="wwwroot\**\*" />
</ItemGroup>
关于asp.net - 映射到 ASP.Net 4 中的 wwwroot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470123/