ServiceStack 是一个开源的 .NET Web 服务框架,用于构建 RESTful Web 服务和 Web API。当需要从其他服务下载或传递 ServiceStack WebApi 文件时,通常涉及以下几种场景:
// 客户端代码示例 (C#)
var client = new JsonServiceClient("https://api.example.com");
var response = client.Get<FileResponse>("/files/download/123");
// 保存文件到本地
File.WriteAllBytes("downloaded.pdf", response.FileBytes);
// 客户端代码示例 (C#)
var client = new JsonServiceClient("https://api.example.com");
var fileBytes = File.ReadAllBytes("upload.pdf");
var request = new UploadFile { FileName = "upload.pdf", FileBytes = fileBytes };
var response = client.Post(request);
// 服务端代码示例 (C#)
public class FileService : Service
{
public object Get(DownloadFile request)
{
var filePath = MapProjectPath($"~/App_Data/{request.FileId}");
if (!File.Exists(filePath))
throw HttpError.NotFound("File not found");
return new HttpResult(new FileInfo(filePath), asAttachment: true);
}
public object Post(UploadFile request)
{
var filePath = MapProjectPath($"~/App_Data/{request.FileName}");
File.WriteAllBytes(filePath, request.FileBytes);
return new UploadFileResponse { FileId = request.FileName };
}
}
问题:传输大文件时可能出现超时或内存不足
解决方案:
// 流式下载示例
public Stream Get(DownloadLargeFile request)
{
var filePath = MapProjectPath($"~/App_Data/{request.FileId}");
return File.OpenRead(filePath);
}
// 流式上传示例
public object Post(UploadLargeFile request)
{
using (var fileStream = File.Create(MapProjectPath($"~/App_Data/{request.FileName}")))
{
Request.InputStream.CopyTo(fileStream);
}
return new UploadFileResponse { Success = true };
}
问题:从不同域下载文件时可能遇到 CORS 限制
解决方案:
// 在 AppHost 中配置 CORS
Plugins.Add(new CorsFeature(
allowOriginWhitelist: new[] { "http://example.com" },
allowCredentials: true,
allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",
allowedHeaders: "Content-Type"
));
问题:需要验证上传文件的类型、大小等
解决方案:
public object Post(UploadFile request)
{
// 验证文件大小 (10MB限制)
if (request.FileBytes.Length > 10 * 1024 * 1024)
throw new ArgumentException("File size exceeds 10MB limit");
// 验证文件类型
var allowedExtensions = new[] { ".pdf", ".docx", ".xlsx" };
var fileExt = Path.GetExtension(request.FileName);
if (!allowedExtensions.Contains(fileExt))
throw new ArgumentException("Invalid file type");
// 保存文件...
}
// 断点续传示例 (客户端)
var client = new JsonServiceClient("https://api.example.com");
var filePath = "largefile.zip";
var fileInfo = new FileInfo(filePath);
var existingSize = fileInfo.Exists ? fileInfo.Length : 0;
var request = new DownloadPartialFile {
FileId = "123",
Range = $"bytes={existingSize}-"
};
var response = client.Get(request);
using (var stream = new FileStream(filePath, FileMode.Append))
{
stream.Write(response.FileBytes, 0, response.FileBytes.Length);
}
通过以上方法和示例,您可以有效地实现 ServiceStack WebApi 的文件传输功能,并解决常见的相关问题。
没有搜到相关的文章