从ModelBinder

时间:2015-05-13 18:11:08

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

我有一个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进行响应,并在此时结束请求的执行?

2 个答案:

答案 0 :(得分:1)

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

我想是一个更高级别的问题,你能不能用它来装饰动作 [Authorize]属性,因为您希望在授权失败时结束执行。

答案 1 :(得分:0)

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

ModelBinder的:

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