经过几次测试后,我作为示例发布的服务器端代码似乎是正确的。这是一个示例,删除了任何身份验证/授权/错误处理代码:
[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);
}
}
一个简单的控制台应用程序足以测试它(使用 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);
}
2018年5月9日编辑:
如中所述这条评论,如果您计划支持带有扩展名的文件名({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>
请注意,由于各种限制,某些文件名将无法使用。例如,您不能命名路径段.
or ..
由于 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>