从ModelState中删除Required类型的错误

时间:2017-01-09 07:10:35

标签: c# asp.net linq asp.net-core

我想在模型状态中忽略类型Required的错误,如果是PATCH http请求,我允许部分更新:

public class ValidateModelFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {

        if (!context.ModelState.IsValid && context.HttpContext.Request.Method == "PATCH")
        {

            // can't figure out this part
            var modelStateErrors = context.ModelState.Keys.SelectMany(key => context.ModelState[key].Errors);
            // get errors of type required from the modelstate
            // context.ModelState.Remove("attribute_which_failed_due_to_required");


        }
        if (!context.ModelState.IsValid)
        {
            var modelErrors = new Dictionary<string, Object>();
            modelErrors["message"] = "The request has validation errors.";
            modelErrors["errors"] = new SerializableError(context.ModelState);
            context.Result = new BadRequestObjectResult(modelErrors);
        }
    }
}

控制器操作:

[ValidateModelFilter]
[HttpPatch("{id}")]
public virtual async Task<IActionResult> Update([FromRoute] int id, [FromBody] TEntity updatedEntity)
{
    TEntity entity = repository.GetById<TEntity>(id);
    if (entity == null)
    {
        return NotFound(new { message = $"{EntityName} does not exist!" });
    }
    repository.Update(entity, updatedEntity);
    await repository.SaveAsync();
    return NoContent();
}

那么,如何过滤掉“必需”类型错误并将其从模型状态中删除。

2 个答案:

答案 0 :(得分:0)

不幸的是,没有比做一些反思更好的选择了。我设法使用下面的代码找到必填字段。

foreach (string parameter in context.ModelState.Keys)
{
    string[] parameterParts = parameter.Split('.');
    string argumentName = parameterParts[0];
    string propertyName = parameterParts[1];
    var argument = context.ActionArguments[argumentName];
    var property = argument.GetType().GetProperty(propertyName);
    if (property.IsDefined(typeof(RequiredAttribute), true))
    {
        // Your logic
    }
}

答案 1 :(得分:0)

这是我做的:

    public override void OnActionExecuting(ActionExecutingContext context)
    {

        if (!context.ModelState.IsValid && context.HttpContext.Request.Method == "PATCH")
        {
            var modelStateErrors = context.ModelState.Where(model =>
            {
                // ignore only if required error is present
                if (model.Value.Errors.Count == 1)
                {
                    // assuming required validation error message contains word "required"
                    return model.Value.Errors.FirstOrDefault().ErrorMessage.Contains("required");
                }
                return false;
            });
            foreach (var errorModel in modelStateErrors)
            {
                context.ModelState.Remove(errorModel.Key.ToString());
            }

        }
        if (!context.ModelState.IsValid)
        {
            var modelErrors = new Dictionary<string, Object>();
            modelErrors["message"] = "The request has validation errors.";
            modelErrors["errors"] = new SerializableError(context.ModelState);
            context.Result = new BadRequestObjectResult(modelErrors);
        }
    }