使用ASP.Net Web Api 2中的PUT动词上传文件

Max*_*ini 7 c# file-upload http asp.net-web-api asp.net-web-api2

我想使用HTTP PUT动词公开ASP.Net Web Api 2动作来上传文件.这与我们的REST模型一致,因为API代表一个远程文件系统(类似于WebDAV,但实际上是简化的),因此客户端选择资源名称(因此PUT是理想的,POST不是一个合理的选择).

Web Api文档描述了如何使用multipart/form-data表单上载文件,但没有描述如何使用PUT方法进行上传.

您将使用什么来测试这样的API(HTML多部分表单不允许PUT动词)?服务器实现是否类似于web api文档中描述的多部分实现(使用MultipartStreamProvider),或者应该如下所示:

[HttpPut]
public async Task<HttpResponseMessage> PutFile(string resourcePath)
{
    Stream fileContent = await this.Request.Content.ReadAsStreamAsync();
    bool isNew = await this._storageManager.UploadFile(resourcePath, fileContent);
    if (isNew)
    {
        return this.Request.CreateResponse(HttpStatusCode.Created);
    }
    else
    {
        return this.Request.CreateResponse(HttpStatusCode.OK);
    }
}
Run Code Online (Sandbox Code Playgroud)

Max*_*ini 10

经过几次测试后,我发布的服务器端代码似乎是正确的.这是一个示例,从任何身份验证/授权/错误处理代码中删除:

[HttpPut]
[Route(@"api/storage/{*resourcePath?}")]
public async Task<HttpResponseMessage> PutFile(string resourcePath = "")
{
    // Extract data from request
    Stream fileContent = await this.Request.Content.ReadAsStreamAsync();
    MediaTypeHeaderValue contentTypeHeader = this.Request.Content.Headers.ContentType;
    string contentType =
        contentTypeHeader != null ? contentTypeHeader.MediaType : "application/octet-stream";

    // Save the file to the underlying storage
    bool isNew = await this._dal.SaveFile(resourcePath, contentType, fileContent);

    // Return appropriate HTTP status code
    if (isNew)
    {
        return this.Request.CreateResponse(HttpStatusCode.Created);
    }
    else
    {
        return this.Request.CreateResponse(HttpStatusCode.OK);
    }
}
Run Code Online (Sandbox Code Playgroud)

一个简单的控制台应用程序足以测试它(使用Web Api客户端库):

using (var fileContent = new FileStream(@"C:\temp\testfile.txt", FileMode.Open))
using (var client = new HttpClient())
{
    var content = new StreamContent(fileContent);
    content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
    client.BaseAddress = new Uri("http://localhost:81");
    HttpResponseMessage response =
        await client.PutAsync(@"/api/storage/testfile.txt", content);
}
Run Code Online (Sandbox Code Playgroud)

编辑2018-05-09:

正如指出此评论,如果您打算支持文件名的扩展名({filename}.{extension})不强制客户追加结尾的斜线,您将需要修改你的web.config到IIS绑定到你的Web API应用程序对这些文件类型,默认情况下,IIS将使用静态文件处理程序来处理看起来像文件名的内容(即包含点的最后一个路径段的URL).我的system.webServer部分看起来像:

<system.webServer>
    <handlers>
      <!-- Clear all handlers, prevents executing code file extensions or returning any file contents. -->
      <clear />
      <!-- Favicon static handler. -->
      <add name="FaviconStaticFile" path="/favicon.ico" verb="GET" modules="StaticFileModule" preCondition="integratedMode" resourceType="File" requireAccess="Read" />
      <!-- By default, only map extensionless URLs to ASP.NET -->
      <!-- (the "*." handler mapping is a special syntax that matches extensionless URLs) -->
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <!-- API endpoints must handle path segments including a dot -->
      <add name="ExtensionIncludedUrlHandler-Integrated-4.0" path="/api/storage/*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

请注意,由于各种限制,某些文件名将无法使用.例如,您无法命名路径段,.或者..因为RFC需要替换它,Azure托管服务将不允许冒号作为路径段的最后一个字符,并且IIS默认禁止一组字符.

您可能还希望增加IIS/ASP.NET文件上载大小限制:

<!-- Path specific settings -->
<location path="api/storage">
  <system.web>
    <httpRuntime maxRequestLength="200000000" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="200000000" />
      </requestFiltering>
    </security>
    </system.webServer>
</location>
Run Code Online (Sandbox Code Playgroud)