Reading a file from a UNC path and setting the cor

2019-02-20 14:20发布

问题:

How would I go about reading a file from a UNC path, discovering the proper MIME type, and streaming that out to a browser?

It feels to me like I'm re-inventing IIS, and I'll also have to maintain my own MIME type database for each file extension. Does the above request sound reasonable, or is there a better way?

I plan on streaming this out via a browser HTTP Get request on IIS7. If it matters, I'm also running Cognos on the same server. Any framework is OK (WCF, ASPX, etc)

回答1:

Using WCF its pretty basic: This code can be hosted under IIS/Service/WAS/etc.
I never found a convenient way to handle the mime type, you will need to have your own db that will map file extension into mime types.

[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface IMediaRetriver
{
  [OperationContract]
  [WebGet(UriTemplate = "/get?f={fileName}")]
  Stream Get(string fileName);
}


[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MediaRetriver : IMediaRetriver
{
    public Stream Get(string fileName)
    {
        // pro tips
        // this will cause the file dialog to show the file name instead of "get"
        WebOperationContext.Current.OutgoingResponse.Headers.Add(
          "Content-disposition", string.Format("inline; filename={0}", fileName));           
        WebOperationContext.Current.OutgoingResponse.ContentType = 
           "application/octet-stream";

        // you want to add sharing here also
        return File.Open(fileName)
    }
}