MediaTypeFormatters を使用する以外に、AspNet WebAPI でインターフェイスをサポートする方法があるかどうかを知る必要がありますか?
1 に答える
1
上記のコメントに基づいて、アクションの宣言された戻り値の型ではなく、インスタンス型でコンテンツ ネゴシエーションが発生することを探していますか? 既定では、Web API は宣言された戻り値の型を使用してコンテンツ ネゴシエーションを行います。
はいの場合、現在これを達成する明確な方法はありませんが、次の回避策を使用できます。
例:
public HttpResponseMessage GetEntity()
{
IEntity derivedEntityInstance = new Person()
{
Id = 10,
Name = "Mike",
City = "Redmond"
};
IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();
ContentNegotiationResult negotiationResult = negotiator.Negotiate(derivedEntityInstance.GetType(), this.Request, this.Configuration.Formatters);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ObjectContent(derivedEntityInstance.GetType(), derivedEntityInstance, negotiationResult.Formatter);
response.Content.Headers.ContentType = negotiationResult.MediaType;
return response;
}
注: 近日中にリリースされる予定のリリースでは、これを実現する簡単な方法を提供しています。
編集:あなたのコメントに基づいて、以下は例です。私が話していたリリースはすでに出ています。パッケージをバージョンにアップグレードできます5.0.0-beta2
。この後、次のようにすることができます。
public IHttpActionResult GetEntity()
{
IEntity derivedEntityInstance = new Person()
{
Id = 10,
Name = "Mike",
City = "Redmond"
};
// 'Content' method actually creates something called 'NegotiatedContentResult'
// which handles with content-negotiating your response.
// Here if you had specified 'return Content<BaseEntityType>(HttpStatusCode.OK, derivedEntityInstance)', then the content-negotiation would have occurred based on your 'BaseEntityType', otherwise if you do like below, it would try to get the type out of the derivedEntityInstance and does con-neg on it.
return Content(HttpStatusCode.OK, derivedEntityInstance);
}
お役に立てれば。
于 2013-06-24T20:38:58.390 に答える