【问题标题】:How to call Web API action with a dot at the end of the URL?如何在 URL 末尾使用点调用 Web API 操作?
【发布时间】:2015-08-28 09:38:19
【问题描述】:

这是我研究实现从 web api 下载文件的link,我尝试使用这些 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);
}

控制器

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 }
            );

【问题讨论】:

标签: asp.net asp.net-web-api2


【解决方案1】:

默认情况下,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>

查看此链接:http://average-joe.info/allow-dots-in-url-iis/

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 2017-06-20
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多