新建一个类
public class FileOperation: IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.operationId.ToLower().Contains("download"))
{
operation.produces = new[] { "application/octet-stream", "application/json" };
operation.responses["200"].schema = new Schema { type = "file", description = "Download file" };
}
}
}
自定义swagger下载文件
c.OperationFilter<FileOperation>();
调用--route包含download即可识别
[HttpPost, Route("Download_xx")]
public HttpResponseMessage Download_xx()
{
try
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data\\Model\\1.xlsx");
var stream = new FileStream(path, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = System.Web.HttpUtility.UrlEncode("test.xlsx", Encoding.UTF8)
};
return response;
}
catch(Exception ex)
{
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}