我需要知道除了使用 MediaTypeFormatters 之外,是否有其他方法可以支持 AspNet WebAPI 中的接口?
user1624372
问问题
404 次
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 回答