C# Web Api忽略属性中的CreateErrorResponse
我有一个基本控制器:C# Web Api忽略属性中的CreateErrorResponse,c#,asp.net-web-api,C#,Asp.net Web Api,我有一个基本控制器: public abstract class EntityController<T> : ApiController { [HttpPost] [ValidateModel] public abstract IHttpActionResult Create(T dto); [HttpPut] [ValidateModel] public abstract IHttpActionResult Update(T dto
public abstract class EntityController<T> : ApiController
{
[HttpPost]
[ValidateModel]
public abstract IHttpActionResult Create(T dto);
[HttpPut]
[ValidateModel]
public abstract IHttpActionResult Update(T dto);
[HttpDelete]
public abstract IHttpActionResult Delete(int id);
}
public class CustomerTypeController : EntityController<CustomerTypeDTO>
{
[ApiAuthorize(Right = Rights.CustomerType, Action = Action.Create)]
public override IHttpActionResult Create(CustomerTypeDTO customerType)
{
return Save(customerType);
}
[ApiAuthorize(Right = Rights.CustomerType, Action = Action.Update)]
public override IHttpActionResult Update(CustomerTypeDTO customerType)
{
return Save(customerType);
}
private IHttpActionResult Save(CustomerTypeDTO customerType)
{
//service layer save customer type
}
}
然而,问题是,即使属性创建了错误响应,操作仍然会进入ValidateModel,然后进入操作本身
如何才能阻止api在Authorize和ValidateModel级别进一步处理请求?问题在于Authorize属性代码没有设置响应。它必须是这样的:
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
//Do some checks...
if (!authorized)
actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, new CustomNotAuthorizedException());
}
}
if (!authorized)
{
var response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, new CustomNotAuthorizedException());
actionContent.Response = response;
}