I have an MVAP 4 WebAPI application. What I want to do is filter out any errors ModelStatethat occur due to garbled data sent during put / post.
I have ActionFilterAttributeone that checks if it really is ModelState. I want to send the state ErrorMessageback to the user. This part is working fine.
public class MyValidationFilter :System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
ErrorResponse errorResponse = new ErrorResponse();
foreach (var key in actionContext.ModelState.Keys)
{
var state = actionContext.ModelState[key];
if (state.Errors.Any())
{
string validationMessage = state.Errors.First().ErrorMessage;
errorResponse.ErrorMessages.Add(new ErrorMessage(validationMessage));
}
}
throw new WebAPIException(HttpStatusCode.BadRequest, errorResponse );
}
}
}
A regular check (required, StringLength, Regex) everything works fine, because I can manage these messages.
[Required(ErrorMessage = "ID is required")]
public string ID { get; set; }
However, I cannot control the message if someone is transmitting incorrectly formatted XML or JSON data. If this happens, I can get
Unterminated string. Expected delimiter: Path, line 1, position 9.
or
. ':' : }. '', 1, 9.
, .
\ "Medium \" 'MyNameSpace.Tenant.WebAPIs.Library.IndividualRegistrationInfo. '', 1, 8.
1- 7. 'IndividualRegistrationInfo' 'Http://schemas.datacontract.org/2004/07/MyNameSpace.Tenant.WebAPIs.Library.IndividualRegistrationInfo'.. Encountered 'Element' 'asdf', namespace ''
- " ", . , , - , ?
UPDATE
:
2 Formatters JSON XML.
public class JsonFormatter : JsonMediaTypeFormatter
{
public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
{
System.Threading.Tasks.Task<object> task = base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger);
if (task.Result == null)
{
}
return task;
}
}
public class XMLFormatter : XmlMediaTypeFormatter
{
public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
{
System.Threading.Tasks.Task<object> task = base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger);
if (task.Result == null)
{
}
return task;
}
}
Application_Start global.asax
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonFormatter());
GlobalConfiguration.Configuration.Formatters.Insert(1, new XMLFormatter());
, , .