我在ASP.NET MVC中将存储在数据库中的文件发送回用户时遇到问题.我想要的是一个列出两个链接的视图,一个用于查看文件并让发送给浏览器的mimetype确定应该如何处理,另一个用于强制下载.
如果我选择查看调用的文件SomeRandomFile.bak并且浏览器没有关联的程序来打开这种类型的文件,那么我没有问题,它默认为下载行为.但是,如果我选择查看调用的文件,SomeRandomFile.pdf或者SomeRandomFile.jpg我希望文件只是打开.但是我也希望将下载链接保留在一边,这样无论文件类型如何,我都可以强制下载提示.这有意义吗?
我已经尝试过FileStreamResult它适用于大多数文件,它的构造函数默认不接受文件名,因此根据url(根据内容类型不知道要提供的扩展名)为未知文件分配文件名.如果我通过指定强制文件名,我将失去浏览器直接打开文件的能力,我得到一个下载提示.有人遇到过这种情况么.
这些是我迄今为止尝试过的例子.
//Gives me a download prompt.
return File(document.Data, document.ContentType, document.Name);
Run Code Online (Sandbox Code Playgroud)
//Opens if it is a known extension type, downloads otherwise (download has bogus name and missing extension)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);
Run Code Online (Sandbox Code Playgroud)
//Gives me a download prompt (lose the ability to open by default if known type)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name};
Run Code Online (Sandbox Code Playgroud)
有什么建议?
有时我在向WebService执行HttpWebRequest时遇到以下错误.我也复制了下面的代码.
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:80 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = …Run Code Online (Sandbox Code Playgroud) .net c# socketexception system.net.webexception asp.net-web-api2