Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Web Api忽略属性中的CreateErrorResponse_C#_Asp.net Web Api - Fatal编程技术网

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