除了使用MediaTypeFormatters之外,有没有办法在AspNet WebAPI控制器动作中支持接口?

时间:2013-06-24 17:11:15

标签: interface asp.net-web-api

我需要知道除了使用MediaTypeFormatters之外,是否有办法支持AspNet WebAPI中的接口?

1 个答案:

答案 0 :(得分: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);
}

希望这有帮助。