我有一个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,并在该点结束请求的执行?
发布于 2015-05-14 02:28:26
您可以在ModelBinder和操作中使用actionContext.ModelState.IsValid吗?
我猜是一个更高层次的问题,既然您想在授权失败时结束执行,那么您是否能够仅使用[Authorize]属性来修饰操作。
发布于 2015-05-14 02:41:06
根据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());https://stackoverflow.com/questions/30222330
复制相似问题