简体   繁体   English

WebApi文件读取访问被拒绝

[英]WebApi File Read Access is Denied

I have a WebApi application whose intent is to serve up audio files, located within the application. 我有一个WebApi应用程序,其目的是在应用程序内提供音频文件。 They are stored in the app_data/audio folder. 它们存储在app_data / audio文件夹中。

Here is my method of retrieval: 这是我的检索方法:

public HttpResponseMessage Get(string file)
    {
        var path = String.Format("{0}{1}", HttpContext.Current.Server.MapPath(@"~/App_Data/Audio/"), file);

        try
        {
            var responseStream = new MemoryStream();
            using (Stream fileStream = File.Open(path, FileMode.Open))
            {
                fileStream.CopyTo(responseStream);
                fileStream.Close();
                responseStream.Position = 0;
            }
            var response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StreamContent(responseStream)
                };

            response.Content.Headers.Add("content-type", "audio/basic"); 
            response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                Private = true
            };

            response.Content.Headers.Expires = null;
            response.Headers.Pragma.Clear();

            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = file
            };

            return response;
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, e.Message);
        }
    }

Unfortunately, I get this error: 不幸的是,我得到这个错误:

"Access to the path 'F:\\Apps\\AudioServeup\\App_Data\\Audio\\test.pcm' is denied." “拒绝访问路径'F:\\ Apps \\ AudioServeup \\ App_Data \\ Audio \\ test.pcm'。”

I can resolve this by setting the AppPool identity to NetworkService, then giving NetworkService Write Access . 我可以通过将AppPool身份设置为NetworkService,然后给予NetworkService Write Access来解决此问题。 Huh? 咦? Not sure why I would require that, because NetworkService has read access by default. 不知道为什么要这样做,因为默认情况下NetworkService具有读取访问权限。

Any ideas? 有任何想法吗?

Thanks! 谢谢!

尝试File.OpenRead(而不是File.Open(因为这将确保它仅在打开文件时请求读取访问权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM