覆盖ExecuteAsync方法以避免重复Web Api Action Method的代码

时间:2016-03-05 03:26:11

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

在我的api控制器动作方法中。我正在使用内容协商获取请求。代码是:

 
IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();
ContentNegotiationResult result = negotiator.Negotiate(typeof(OfficeDetailsDto), this.Request, this.Configuration.Formatters);
if (result == null)
{
    var responseErr = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
    throw new HttpResponseException(responseErr);
}

但是现在我想通过继承 ApiController 来创建 BaseAPIController 控制器,并希望覆盖基类的方法以获得上述代码,以便我不必在所有控制器类中反复编写此代码。它还将使我的控制器动作方法变薄。

请有人给我任何建议或样品。

1 个答案:

答案 0 :(得分:2)

ApiController 已经提供了开箱即用的内容协商功能,但是如果你真的想要定制内容,你可以创建自己的通用方法,你可以从继承的控制器调用这些方法。谈判过程。

您的BaseAPIController

public abstract class BaseAPIController : ApiController {    
    protected virtual HttpResponseMessage NegotiatedContent<T>(HttpStatusCode statusCode, T content) {
        var type = typeof(T);
        var request = this.Request;
        var formatters = this.Configuration.Formatters;
        var negotiator = this.Configuration.Services.GetContentNegotiator();

        var result = negotiator.Negotiate(type, request, formatters );
        if (result == null) {
            var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
            throw new HttpResponseException(response));
        }

        return new HttpResponseMessage() {
            StatusCode = statusCode,
            Content = new ObjectContent<T>(
                content,                    // What we are serializing 
                result.Formatter,           // The media formatter
                result.MediaType.MediaType  // The MIME type
            )
        };
    }    
}

此代码等同于ApiController自动提供的代码。

具有更薄的操作方法的潜在OfficeDetailsController

public class OfficeDetailsController : BaseAPIController {    
    public HttpResponseMessage GetOfficeDetails(int id) {
        var item = new OfficeDetailsDto() { Id = id, Name = "Gizmo"};
        // what ever else needs to be done to the item
        // ...    
        return NegotiatedContent(HttpStatusCode.Ok, item);
    }
}

以下是使用ApiController默认值执行相同操作的示例。

public class OfficeDetailsController : ApiController {    
    public IHttpActionResult GetOfficeDetails(int id) {
        var item = new OfficeDetailsDto() { Id = id, Name = "Gizmo"};
        // what ever else needs to be done to the item
        // ...    
        return Ok(item);
    }
}