0
我需要訪問自定義DataAnnotation屬性內的屬性。如何訪問此屬性以設置響應值?該屬性被添加到模型屬性。Web API - 訪問ActionFilterAttribute內部的自定義屬性屬性OnActionExecuting
public class BirthDateAttribute : ValidationAttribute
{
public string ErrorCode { get; set; }
....
}
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
List<Errors> errors = new List<Errors>();
// Set error message and errorCode
foreach (var key in keys)
{
if (!actionContext.ModelState.IsValidField(key))
{
error.Add(new HttpResponseError
{
Code = ???????????,
Message = actionContext.ModelState[key].Errors.FirstOrDefault().ErrorMessage
});
}
}
// Return to client
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.BadRequest, errors);
}
}
}
它適用於模型屬性。 – PsychoDUCK
修改了答案。希望這可以幫助! –