【发布时间】:2017-02-14 23:16:41
【问题描述】:
在我的 ASP.NET Web API 应用程序中,我有一个这样的控制器:
[RoutePrefix("api/ratings")]
public class RateCostumerController : ApiController
{
[AllowAnonymous]
[Route("Report/GetReport")]
[HttpGet]
public HttpResponseMessage ExportReport([FromUri] string costumer)
{
var rd = new ReportDocument();
/*No relevant code here*/
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(ms.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "Reporte.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
所以,当我使用客户参数发出一个简单的 GET 请求时,我会在浏览器中得到一个 pdf 文件作为响应。一些响应头:
内容处置:附件;文件名=Reporte.pdf 内容长度:22331 内容类型:应用程序/八位字节流
在我的 Xamarin PCL 项目中设置 swagger、生成 json 元数据文件并使用它生成 C# 代码后,我尝试使用该服务。 但它失败了,因为在生成的代码中试图反序列化 json,但不是 json 结果!
这里是生成代码失败的部分:
[...]
var _result = new Microsoft.Rest.HttpOperationResponse<object>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
[...]
当我调试时,我发现文件的内容在正文中,所以反序列化把它搞砸了。由于不建议编辑此生成的类文件,我需要在我的 API 中进行哪些更改才能正确生成 application/octet-stream content-response 的代码?
【问题讨论】:
-
您是否尝试过使用 Swagger Codegen 来生成 C# API 客户端? Swagger Codegen 生成的 C# API 客户端应该能够处理
file下载。 -
我找到了使它工作的过滤器的代码。但是生成的代码仍然存在问题。一旦解决,我会在这里发布
标签: c# json asp.net-web-api swagger