tso*_*tan 5 asp.net asp.net-web-api2
这是我研究的用于实现从 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);
}
Run Code Online (Sandbox Code Playgroud)
控制器
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;
}
}
Run Code Online (Sandbox Code Playgroud)
WebAPI配置
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{filename}",
defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
默认情况下,IIS 会阻止对其无法识别的任何文件类型的访问。如果 URL 中包含点 (.),IIS 会假定其为文件名并阻止访问。
\n\n要允许 IIS 站点上的 URL 中包含点(可能是 MVC 路由路径中的域名/电子邮件地址/等),您必须进行一些更改。
\n\n快速解决
\n\n一个简单的选择是在末尾添加一个 /。这告诉 IIS 它是一个文件路径而不是一个文件。
\n\nhttp://localhost:49932/api/simplefiles/1.zip变成http://localhost:49932/api/simplefiles/1.zip/.
然而,这并不理想:手动输入 URL 的客户可能会忽略前导斜杠。
\n\n您可以通过添加以下内容来告诉 IIS 不要打扰您:
\n\n<system.webServer>\n <modules runAllManagedModulesForAllRequests="true" />\n<system.webServer>\nRun Code Online (Sandbox Code Playgroud)\n\n检查此链接:http://average-joe.info/allow-dots-in-url-iis/
\n| 归档时间: |
|
| 查看次数: |
3435 次 |
| 最近记录: |