所以我有一个实现CRUD的通用基本控制器,它来自APIController
。
public class GenericController<TEntity> : ApiController where TEntity : class {
private readonly GenericModel<TEntity> _model;
public IModel Model {
get { return _model; }
}
public GenericController(IGenericModel<TEntity> model) {
_model = (GenericModel<TEntity>)model;
}
[HttpPost, Route]
public IHttpActionResult Post(TEntity entity) {
TEntity newEntity = _model.Create(entity);
String urlLink = $"{Request.RequestUri}{RequestContext.VirtualPathRoot}{((IGenericEntity)newEntity).ID}";
return Created(urlLink, newEntity);
}
[HttpGet, Route]
public IHttpActionResult GetList() {
return Ok(_model.ReadList());
}
[HttpGet, Route("{ID:int}")]
public IHttpActionResult Get(Int64 ID) {
return Ok(_model.Read(ID));
}
[HttpPut, Route]
public IHttpActionResult Put(TEntity entity) {
_model.Update(entity);
return Ok();
}
[HttpDelete, Route("{ID:int}")]
public IHttpActionResult Delete(Int64 ID) {
_model.Delete(ID);
return Ok();
}
}
并允许通过CustomDirectRouteProvider
继承控制器继承:
config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());
我的CustomDirectRouteProvider在哪里:
public class CustomDirectRouteProvider : DefaultDirectRouteProvider {
protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor) {
return actionDescriptor.GetCustomAttributes<IDirectRouteFactory> (inherit: true);
}
}
这一切都很好用,直到我想覆盖像POST这样的方法。举个例子:
[RoutePrefix(@"api/Test")]
public class DerivedController : GenericController<ConcreteEntity> {
public DerivedController (IGenericModel<ConcreteEntity> model) : base(model) {
}
[HttpPost, Route]
public new IHttpActionResult Post(ConcreteEntity entity) {
//New Post Functionality Here
}
}
此时我收到错误:
"Multiple actions were found that match the request"
所以我的问题是,如何覆盖路线本身?我基本上希望我的新POST优先于通用的POST。我认为凭借隐藏的通用路线/方法,这只会起作用,但是我的想法是不正确的。
答案 0 :(得分:3)
能够重新创建您的问题,通过试验和错误的过程能够通过使GenericController
成为一个抽象类来实现它的工作
public abstract class GenericController<TEntity> : ApiController where TEntity : class {
[HttpPost, Route]
public virtual IHttpActionResult Post(TEntity entity) {
TEntity newEntity = _model.Create(entity);
String urlLink = $"{Request.RequestUri}{RequestContext.VirtualPathRoot}{((IGenericEntity)newEntity).ID}";
return Created(urlLink, newEntity);
}
}
并删除DerivedController
的继承操作的属性,因为它们与继承的类匹配
[RoutePrefix(@"api/Test")]
public class DerivedController : GenericController<ConcreteEntity> {
public DerivedController (IGenericModel<ConcreteEntity> model) : base(model) {
}
public override IHttpActionResult Post(ConcreteEntity entity) {
//New Post Functionality Here
}
}