覆盖 ExecuteAsync 方法以避免重复 Web Api 操作方法的代码

Override ExecuteAsync Method to avoid repeating code of Web Api Action Method

在我的 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 控制器并想 覆盖一个基础 class 的方法 有上面的代码,这样我就不必在我的所有控制器中一次又一次地编写这段代码 classes。它还将使我的控制器操作方法变薄。

谁能给我任何建议或样品。

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);
    }
}