DataAnnotation para la propiedad requerida
Primero funciona, pero hoy ha fallado!
Así es como defino la propiedad date:
[Display(Name = "Date")]
[Required(ErrorMessage = "Date of Submission is required.")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime TripDate { get; set; }
Ha estado funcionando en el pasado. Pero hoy, cuando llamo a la misma acción de ApiController:
[HttpPost]
public HttpResponseMessage SaveNewReport(TripLeaderReportInputModel model)
Los informes Firebug:
ExceptionMessage:
"Property 'TripDate' on type 'Whitewater.ViewModels.Report.TripLeaderReportInputModel'
is invalid. Value-typed properties marked as [Required] must also be marked with
[DataMember(IsRequired=true)] to be recognized as required. Consider attributing the
declaring type with [DataContract] and the property with [DataMember(IsRequired=true)]."
ExceptionType
"System.InvalidOperationException"
¿Qué pasó? ¿No son esos [DataContract]
para WCF
? Estoy usando el REST WebAPI
en MVC4
!
Alguien Puede ayudar? por favor?
---actualización---
Hay algunos enlaces similares que he encontrado.
MvC 4.0 RTM nos rompió y no sabemos cómo arreglarlo RSS
- - - actualizar de nuevo - - -
Aquí está el encabezado de respuesta HTTP:
Cache-Control no-cache
Connection Close
Content-Length 1846
Content-Type application/json; charset=utf-8
Date Thu, 06 Sep 2012 17:48:15 GMT
Expires -1
Pragma no-cache
Server ASP.NET Development Server/10.0.0.0
X-AspNet-Version 4.0.30319
Encabezado de solicitud:
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Cache-Control no-cache
Connection keep-alive
Content-Length 380
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Cookie .ASPXAUTH=1FF35BD017B199BE629A2408B2A3DFCD4625F9E75D0C58BBD0D128D18FFDB8DA3CDCB484C80176A74C79BB001A20201C6FB9B566FEE09B1CF1D8EA128A67FCA6ABCE53BB7D80B634A407F9CE2BE436BDE3DCDC2C3E33AAA2B4670A0F04DAD13A57A7ABF600FA80C417B67C53BE3F4D0EACE5EB125BD832037E392D4ED4242CF6
DNT 1
Host localhost:39019
Pragma no-cache
Referer http://localhost:39019/Report/TripLeader
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0
X-Requested-With XMLHttpRequest
--- actualización ---
He encontrado una solución improvisada. Consulte la respuesta a continuación. Si alguien entiende por qué funciona o tiene mejores soluciones, por favor publique sus respuestas. Agradecer.
4 answers
Bien. Aunque no he entendido completamente esta cosa. Se encuentra una solución alternativa.
En Global.asax
:
GlobalConfiguration.Configuration.Services.RemoveAll(
typeof(System.Web.Http.Validation.ModelValidatorProvider),
v => v is InvalidModelValidatorProvider);
Lo encontré en el Gestor de incidencias de aspnetwebstack. Aquí está el enlace a la página:
Si alguien puede decirnos por qué es así, por favor publique su visión como respuestas. Agradecer.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-29 14:12:37
He añadido un ModelValidationFilterAttribute
y lo he hecho funcionar:
public class ModelValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
// Return the validation errors in the response body.
var errors = new Dictionary<string, IEnumerable<string>>();
//string key;
foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState)
{
//key = keyValue.Key.Substring(keyValue.Key.IndexOf('.') + 1);
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
//var errors = actionContext.ModelState
// .Where(e => e.Value.Errors.Count > 0)
// .Select(e => new Error
// {
// Name = e.Key,
// Message = e.Value.Errors.First().ErrorMessage
// }).ToArray();
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
}
Puede agregar [ModelValidation]
filtro en las acciones. O añádelo a Global.asax.cs
:
GlobalConfiguration.Configuration.Services.RemoveAll(
typeof(System.Web.Http.Validation.ModelValidatorProvider),
v => v is InvalidModelValidatorProvider);
De esta manera, continúo usando la anotación de datos original.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-20 18:03:25
ACTUALIZACIÓN 24-5-2013: El InvalidModelValidatorProvider
responsable de este mensaje de error ha sido eliminado del ASP.NET pila de tecnología. Este validador probó causar más confusión de la que estaba destinado a resolver. Para obtener más información, consulte el siguiente enlace: http://aspnetwebstack.codeplex.com/workitem/270
Cuando decora su clase con el atributo [DataContract]
, necesita decorar explícitamente los miembros que desea serializar con el atributo [DataMember]
.
El problema es que DataContractSerializer
no soporta el atributo [Required]
. Para los tipos de referencia, podemos comprobar que el valor no es nulo después de la deserialización. Pero para los tipos de valor, no hay manera de hacer cumplir la semántica [Required]
para DataContractSerializer
sin [DataMember(IsRequired=true)]
.
Por lo que podría terminar marcando un DateTime
como [Required]
y esperar un error de validación del modelo si el DateTime
no se envía, pero solo obtendría un valor DateTime.MinValue
y ningún error de validación en su lugar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-24 11:13:57
Si está intentando devolver el resultado de su acción como XML, deberá utilizar DataContracts, ya que son requeridos por el serializador predeterminado. Supongo que anteriormente había estado solicitando la salida de su acción como Json, el serializador Json no requiere contratos de datos. ¿Puede publicar un violín de su solicitud?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-06 18:03:30