这是link我研究如何实现从 Web api 下载文件,我尝试使用这些 URL 下载文件
http://localhost:49932/api/simplefiles/1.zip <--不工作,找不到投诉方法 http://localhost:49932/api/simplefiles/1 <--能够调用操作名称,但为什么?
我知道与导致失败的 URL 中的“.zip”扩展名有关,但我只是不明白并且不确定出了什么问题,有人可以解释一下吗?
界面
public interface IFileProvider
{
bool Exists(string name);
FileStream Open(string name);
long GetLength(string name);
}
Controller
public class SimpleFilesController : ApiController
{
public IFileProvider FileProvider { get; set; }
public SimpleFilesController()
{
FileProvider = new FileProvider();
}
public HttpResponseMessage Get(string fileName)
{
if (!FileProvider.Exists(fileName))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
FileStream fileStream = FileProvider.Open(fileName);
var response = new HttpResponseMessage();
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentDisposition
= new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType
= new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength
= FileProvider.GetLength(fileName);
return response;
}
}
WebAPIConfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{filename}",
defaults: new { id = RouteParameter.Optional }
);
最佳答案
默认情况下,IIS 会阻止对其无法识别的任何文件类型的访问。如果 URL 中包含点 (.),IIS 会假定它是一个文件名并阻止访问。
要允许 IIS 站点上的 URL 中包含点(可能是 MVC 路由路径中的域名/电子邮件地址/等),您必须进行一些更改。
快速修复
一个简单的选择是在末尾附加一个/。这告诉 IIS 它是一个文件路径而不是一个文件。
http://localhost:49932/api/simplefiles/1.zip
变为 http://localhost:49932/api/simplefiles/1.zip/
。
但是,这并不理想:手动输入 URL 的客户可能会忽略前导斜杠。
您可以通过添加以下内容来告诉 IIS 不要打扰您:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<system.webServer>
关于asp.net - 如何调用 URL 末尾带有点的 Web API 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32267906/