Myślę, że atrybut jest świetnym pomysłem i dlatego zaimplementowałem atrybut, który może pomóc innym, dopóki go nie wypuścicie.
Udekoruj swoje działania z atrybutem:
public class FooController : ApiController
{
[ResponseType(typeof(Bar))]
public HttpResponseMessage Get(string id)
{
// ...
}
}
Definiowanie atrybutu:
[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; }
}
zdefiniować metodę zarejestrować typy reakcji:
/// <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);
}
}
}
umieścić go na swojej aplikacji początek:
RegisterHelpResponseTypes(typeof(FooController).Assembly);
Proszę dać mi znać, jeśli znajdziesz jakieś problemy.
należy zdefiniować kody stanu wyjątki, które różnią się od tego, co się spodziewać. W aplikacji Restful rozmówcy Twojego API oczekują "200 OK", chyba że wystąpi jakiś błąd. –
@ CharlieBrown: Lub inne kody 2xx, na przykład 201 utworzone. http://pl.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success – SLaks
@SLaks dokładnie dlatego właśnie byłbym wdzięczny za twoją radę na ten temat –