首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未经授权来自ModelBinder的响应

未经授权来自ModelBinder的响应
EN

Stack Overflow用户
提问于 2015-05-14 02:11:08
回答 2查看 88关注 0票数 0

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

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

代码语言:javascript
复制
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,并在该点结束请求的执行?

EN

回答 2

Stack Overflow用户

发布于 2015-05-14 02:28:26

您可以在ModelBinder和操作中使用actionContext.ModelState.IsValid吗?

我猜是一个更高层次的问题,既然您想在授权失败时结束执行,那么您是否能够仅使用[Authorize]属性来修饰操作。

票数 1
EN

Stack Overflow用户

发布于 2015-05-14 02:41:06

根据vandsh的响应,我做了以下更改:

ModelBinder:

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

添加了一个新的过滤器:

代码语言:javascript
复制
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中添加了该过滤器:

代码语言:javascript
复制
GlobalConfiguration.Configuration.Filters.Add(new Api.Filters.ValidModelAttribute());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30222330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档