【发布时间】:2012-08-22 03:24:57
【问题描述】:
在我的 ApiController 类中,我有以下方法来下载服务器创建的文件。
public HttpResponseMessage Get(int id)
{
try
{
string dir = HttpContext.Current.Server.MapPath("~"); //location of the template file
Stream file = new MemoryStream();
Stream result = _service.GetMyForm(id, dir, file);
if (result == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
result.Position = 0;
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
return response;
}
catch (IOException)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
除了默认的下载文件名是它的 id 之外,一切都运行良好,因此用户可能必须每次在另存为对话框中键入他/她自己的文件名。有没有办法在上面的代码中设置一个默认的文件名?
【问题讨论】:
-
你能分享一下你用来调用这个方法的代码吗?
-
@Yasser - 这是一个 Web API 控制器方法 - 它可能通过进入 IIS 并解析它们并查找路由和调用该方法的 Web API 的 HTTP 请求被调用(当然,它也是由测试调用)。
-
GetMyForm() 内部发生了什么?将文件转换为字节流?
-
@MSIslam 之类的。该函数从用户表单中获取信息并在转换为结果流之前创建一个文件。
标签: c# asp.net-web-api