必需我想從模型狀態忽略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();
}
所以,我怎麼能過濾掉「需要」類型的錯誤,並從模型狀態刪除它們。
你的代碼崩潰parameterParts不包含點 –
好吧,請你控制的方法添加到您的問題。還要添加ModelState.Keys來澄清事情。 –
@IzzetYildrim ModelState.Keys簡單的返回鍵名稱爲ID,名稱,顏色等,它甚至包含了按錯鍵的名稱,如果按錯鍵的名字都貼在身上 –