asp.net core modelstate验证自定义错误消息.如何用引号或其他字符代替输入值 &



我得到以下响应从我的asp.net core 3.1 api后,我把自定义模型验证启动

{
"success": "failed",
"message": "fk entity id: The value '<script>alert(1);</script>' is not valid for fk_entity_id."
}

我的启动代码是这样的

private void CustomValidationResponse(IServiceCollection services)
{
services.Configure<ApiBehaviorOptions>(
options => options.InvalidModelStateResponseFactory = actionContext =>
{
return CustomErrorResponse(actionContext);
}
);
}
private BadRequestObjectResult CustomErrorResponse(ActionContext actionContext)
{
var errorRecordList = actionContext.ModelState
.Where(modelError => modelError.Value.Errors.Count > 0)
.Select(modelError => new
{
ErrorField = modelError.Key,
ErrorDescription = modelError.Value.Errors.FirstOrDefault().ErrorMessage
}).ToList();
string concatenatedMessage = string.Empty;
foreach (var error in errorRecordList)
{
concatenatedMessage += error.ErrorField.Replace("_", " ") + ": " + error.ErrorDescription + ",";
}
concatenatedMessage = concatenatedMessage.TrimEndExt(",");
return new BadRequestObjectResult(new
{
success = "failed",
message = concatenatedMessage
});
}

我想要的是在我的消息响应中以某种方式放置一些引号/转义字符来代替值,例如

{"success"failed"消息": "fk实体id:值['alert(1);']对fk_entity_id无效。"}

问题是为了避免xss攻击目前我使用了以下解决方案

private BadRequestObjectResult CustomErrorResponse(ActionContext actionContext)
{
var errorRecordList = actionContext.ModelState
.Where(modelError => modelError.Value.Errors.Count > 0)
.Select(modelError => new
{
ErrorField = modelError.Key,
ErrorDescription = modelError.Value.Errors.FirstOrDefault().ErrorMessage.Replace("<script>", "'[<script>]'").Replace("</script>", "'[</script>]'")
}).ToList();
string concatenatedMessage = string.Empty;
foreach (var error in errorRecordList)
{
concatenatedMessage += error.ErrorField.Replace("_", " ") + ": " + error.ErrorDescription + ",";
}
concatenatedMessage = concatenatedMessage.TrimEndExt(",");
//if(co)
return new BadRequestObjectResult(new
{
success = "failed",
message = concatenatedMessage
//,  errors = errorRecordList
});
}

相关内容

  • 没有找到相关文章

最新更新