gpt4 book ai didi

c# - Owin 仅提供特定文件夹中的文件

转载 作者:太空狗 更新时间:2023-10-29 23:30:58 26 4
gpt4 key购买 nike

所以我在玩 Owin 和 Katana,我想在我的公共(public)文件夹中提供静态文件。

我有一个包含样式表的内容文件夹和一个脚本文件夹。

我的创业公司:

    public void Configuration(IAppBuilder app)
{
#if DEBUG
//when things go south
app.UseErrorPage();
#endif

// Remap '/' to '.\public\'.
// Turns on static files and public files.
app.UseFileServer(new FileServerOptions()
{
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem(@".\public"),
});

}

因此,如果我浏览到 localhost:8861/,我会转到公共(public)文件夹中的 index.html 文件。没关系。但我也可以浏览到我想要阻止的 localhost:8861/Content/style.css。用户需要的一切都应该可以在公用文件夹中访问。所有其余的都应该被阻止。

我怎样才能做到这一点?

最佳答案

如果您需要简单的文件处理,可以绝对控制您要提供或不提供的文件,您可以使用一些中间件来完全控制。我这样做是因为我希望在开发过程中提供未缓存的文件服务。

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Web;

namespace Owin
{
using AppFunc = Func<IDictionary<string, object>, Task>;

public static class DynamicFileExtension
{
/// <summary>
/// ONLY use during development
/// </summary>
public static void UseDynamicFiles(this IAppBuilder app, string baseDirectory)
{
app.Use(new Func<AppFunc, AppFunc>(next => (async context =>
{
var method = (string) context["owin.RequestMethod"];
var requestpath = (string) context["owin.RequestPath"];
var scheme = (string) context["owin.RequestScheme"];
var response = (Stream) context["owin.ResponseBody"];
var responseHeader = (Dictionary<string, string[]>) context["owin.ResponseHeaders"];

if (method == "GET" && scheme == "http")
{
var fullpath = baseDirectory + requestpath;

// block logic...

if (File.Exists(fullpath))
{

using (var file = File.OpenRead(fullpath))
{
await file.CopyToAsync(response);
}

var mime = MimeMapping.GetMimeMapping(fullpath);

responseHeader.Add("Content-Type", new[] {mime});

return;
}
}

await next.Invoke(context);
})));
}
}
}

我不会在生产中使用它,但它对我有用。

关于c# - Owin 仅提供特定文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25535938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com