我正在为所有api响应使用泛型返回类型:
public HttpStatusCode statusCode { get; set; }
public string error { get; set; }
public IDictionary<string, string> errorfor { get; set; }
public T result { get; set; }
并在API中:
/// <summary>
/// GET Order API
/// </summary>
/// <returns> return list of orders {Order} </returns>
public HttpResponseMessage Get(){
var response = new BaseResponseMessage<IList<Order>>();
//some more codes
response.result = orders;
return Request.CreateResponse(HttpStatusCode.OK, response);
}
当然,我的API帮助页面不会在示例响应正文中显示订单。是否可以配置帮助页面生成器以显示泛型类型?谢谢!
答案 0 :(得分:18)
Web API 2.1帮助页面现在执行此操作:http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#help-page
您还可以查看使用新的ResponseTypeAttribute返回标准HttpResponseMessage:
/// <summary>
/// GET Order API
/// </summary>
[ResponseType(typeof(List<Order>))]
public HttpResponseMessage Get()
{
var orders = new List<Order>();
return Request.CreateResponse(HttpStatusCode.OK, orders);
}
答案 1 :(得分:2)
HelpPage无法猜测只有您拥有的签名的操作的返回类型。如您所知,在正常请求期间不会发生HelpPage生成,但这取决于静态信息。
虽然有一个解决方法。您可以在Areas\HelpPage\App_Start\HelpPageConfig.cs
中查看以下注释代码,该代码允许您为操作指定特定的返回类型。
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
我知道这个解决方法对你来说太麻烦,因为你提到过为你的所有行为都有这种签名。
您可以通过创建自定义属性来扩展HelpPage,该属性通知返回类型并在操作上进行装饰。然后,您可以修改已安装的HelpPage代码以查找这些属性。