【问题标题】:Respond Unauthorized from ModelBinder响应未经授权的 ModelBinder
【发布时间】:2015-05-13 18:11:08
【问题描述】:

我有一个 WebApi ModelBinder,用于将 url 中的字符串转换为表示客户端请求的网站段的对象。客户只能访问某些网站段。

我可以处理来自 ModelBinder 的授权吗?现在我正在这样做,它确实返回 401;但是,Api 控制器代码仍然会被执行。

class SegmentModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value == null || String.IsNullOrEmpty(value.AttemptedValue))
            return false;

        if (/*doesn't have access*/)
            actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        else
            bindingContext.Model = /*set object*/;

        return true;
    }
}

如何响应 401 并在此时结束请求的执行?

【问题讨论】:

    标签: asp.net asp.net-web-api authorization


    【解决方案1】:

    你能在 ModelBinder 和动作中都使用actionContext.ModelState.IsValid 吗?

    我猜是一个更高层次的问题,你能用 [Authorize] 属性,因为您想在授权失败时结束执行。

    【讨论】:

    • 谢谢;我根据这个答案发布了我的更改。我不相信我在任何地方都使用了模型状态,所以希望这不会在其他地方引起问题
    【解决方案2】:

    根据 vandsh 的回复,我做了以下更改:

    模型绑定器:

        if (/*doesn't have access*/)
            actionContext.ModelState.AddModelError("Segment", String.Format("Unauthorized Segment: {0}", segment));
        else
            bindingContext.Model = /*set object*/;
    

    添加了一个新的过滤器:

    public class ValidModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
    

    并在 global.asax.cs 中添加了该过滤器:

    GlobalConfiguration.Configuration.Filters.Add(new Api.Filters.ValidModelAttribute());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 2017-03-20
      • 2015-10-04
      • 1970-01-01
      相关资源
      最近更新 更多