【问题标题】:Auto generated help pages with return type HttpResponseMessage自动生成的返回类型为 HttpResponseMessage 的帮助页面
【发布时间】:2013-07-23 03:59:17
【问题描述】:

我希望对 web api 自动生成的帮助页面进行一些澄清。

据我所知,如果我返回一个类型,它将自动生成该操作的帮助页面,并附上一个示例。但是如果我使用 HttpResponseMessage ,那么它无法猜测响应将是什么并且只能对请求参数做出假设是可以理解的。

我使用 HttpResponseMessage 的原因是,当它可能不同于 200 时,建议指明您希望返回的状态码。

那么最佳实践方法是什么才能返回您想要的状态代码,但仍然有帮助页面确定您返回的类型?

【问题讨论】:

  • 您应该为与预期不同的异常定义状态代码。在 Restful 应用程序中,除非出现某种错误,否则 API 的调用者会收到 200 OK
  • @CharlieBrown:或其他 2xx 代码,例如 201 Created。 en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
  • @SLaks 正是这就是为什么我会感谢您对此提出建议
  • @SLaks 谢谢,我应该澄清一下。使用现有的代码,除非没有匹配的代码。在实践中,我很少找到创建自定义状态码的机会。
  • 我澄清了这个问题,因为我知道几个状态代码及其用途,我并不是要定义我自己的状态。我的观点是问题上所说的

标签: c# asp.net-web-api


【解决方案1】:

对于需要返回 HttpResponseMessage 的这些场景,解决方法是使用 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");

注意
在即将发布的版本中,我们将引入一个名为 System.Web.Http.Description.ResponseTypeAttribute 的新属性,您可以向该属性提供一个 System.Type 指示响应的实际类型。这样,您可以从您的操作中返回 HttpResponseMessageIHttpActionResult,并且仍然希望 HelpPage 能够正常工作。

【讨论】:

  • System.Web.Http.Description.ResponseTypeAttribute 在 Web API 2.1 中可用,所以我建议使用这种方法。
  • 好的,但这仍然记录了一种响应。我有一个 PUT 操作,它可能返回 204、202 或 400。后者有一个响应正文
【解决方案2】:

我认为属性是个好主意,所以我实现了一个属性,它可以帮助其他人,直到你们发布它。

用属性装饰你的动作:

public class FooController : ApiController
{
    [ResponseType(typeof(Bar))]
    public HttpResponseMessage Get(string id)
    {
        // ...
    }
}

定义属性:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ResponseTypeAttribute : Attribute
{
   public ResponseTypeAttribute(Type type)
   {
       if (type == null)
       {
           throw new ArgumentNullException("type");
       }

       Type = type;
   }

   public Type Type { get; private set; }
}

定义注册响应类型的方法:

/// <summary>
///     Registers api controller actions which return HttpResponseMessage
///     and include the ResponseType attribute to be populated with web api
///     auto generated help.
/// </summary>
/// <param name="assembly">The assembly to search for</param>
public static void RegisterHelpResponseTypes(Assembly assembly)
{
    var apiControllerTypes = assembly
        .GetTypes().Where(typeof(ApiController).IsAssignableFrom);

    foreach (var apiControllerType in apiControllerTypes)
    {
        var validActions = apiControllerType.GetMethods()
            .Where(method =>
                Attribute.IsDefined(method, typeof(ResponseTypeAttribute))
                &&
                (method.ReturnType == typeof(HttpResponseMessage)));

        foreach (var action in validActions)
        {
            var responseType = (ResponseTypeAttribute)Attribute
                                    .GetCustomAttributes(action)
                                    .Single(x => x is ResponseTypeAttribute);

            var controllerName = apiControllerType.Name.Substring(0, 
                    apiControllerType.Name.LastIndexOf("Controller", 
                                        StringComparison.OrdinalIgnoreCase));
            var actionName = action.Name;

            GlobalConfiguration
                .Configuration
                .SetActualResponseType(responseType.Type, 
                                       controllerName, 
                                       actionName);
        }
    }
}

在您的应用程序开始时包含它:

RegisterHelpResponseTypes(typeof(FooController).Assembly);

如果您发现任何问题,请告诉我。

【讨论】:

  • 您能否提供一个使用示例?我添加了以上所有内容,但没有看到我的返回类型的任何文档。
  • 当您导航到 WebAPI 的帮助页面并转到您使用该属性装饰的控制器/操作时,您到底有什么?
  • 添加属性实现后,我看到示例响应正常工作。但我真正想要的是查看复杂对象(在 HttpResponseMessage 的主体中)的属性的 XML cmets。有没有办法使用这个属性来做到这一点?我在这里发布了我想要做什么的解释:stackoverflow.com/questions/19646987/…
  • 我明白你的意思,但恐怕没有,因为它似乎不受 web api 支持(至少在我拥有的版本上)。
【解决方案3】:

MVC 5 有一个内置属性来设置响应类型。

更多信息在这里: http://thesoftwaredudeblog.wordpress.com/2014/01/05/webapi-2-helppage-using-responsetype-attribute-instead-of-setactualresponsetype/

只需使用:

    ResponseType(typeof([Your_Class]))]

【讨论】:

  • 使用该属性需要添加:using System.Web.Http.Description;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多