2017-01-09 31 views
0

必需我想從模型狀態忽略Required類型的錯誤類型的錯誤,在PATCH HTTP請求的情況下,其中,我允許部分更新:取下的ModelState

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

所以,我怎麼能過濾掉「需要」類型的錯誤,並從模型狀態刪除它們。

回答

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 
    } 
} 
+0

你的代碼崩潰parameterParts不包含點 –

+0

好吧,請你控制的方法添加到您的問題。還要添加ModelState.Keys來澄清事情。 –

+0

@IzzetYildrim ModelState.Keys簡單的返回鍵名稱爲ID,名稱,顏色等,它甚至包含了按錯鍵的名稱,如果按錯鍵的名字都貼在身上 –

-1

這裏是我做過什麼:

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); 
     } 
    } 
+0

這不是一個真正的解決方案。依靠錯誤消息根本不是一個好習慣。此外,您只檢查LINQ中的第一條錯誤消息,因此如果有錯誤消息包含「必需」字,它將使您的所有模型狀態無效。請考慮檢查我的解決方案。 –