ASP.net WebApi - custom message for invalid data

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.

/// <summary>
/// This filter will validate the models that are used in the webapi
/// </summary>
public class MyValidationFilter :System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            //ErrorResponse is just a simple data structure used to hold response
            ErrorResponse errorResponse = new ErrorResponse();

            //loop through each key(field) and see if it has any errors
            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));                      
                }
            }

            //this is a custom exception class that i have that sends the response to the user.
            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);

        //parse error if null
       if (task.Result == null)
       {
           //handle error here.
       }

       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);

        //parse error if null
        if (task.Result == null)
        {
            //handle error here
        }

        return task;
    }
}

Application_Start global.asax

GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonFormatter());
GlobalConfiguration.Configuration.Formatters.Insert(1, new XMLFormatter());

, , .

+5
3

, , , JsonMediaTypeFormatter XmlMediaTypeFormatter . (.. ), IExceptionFilter.

0

:

2 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);

    //parse error if null
   if (task.Result == null)
   {
       //handle error here.
   }

   return task;
}}


public class XMLFormatter : XmlMediaTypeFormatter
{
    public override System.Threading.Tasks.Task ReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
    {

        System.Threading.Tasks.Task task = base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger);

        //parse error if null
        if (task.Result == null)
        {
            //handle error here
        }

        return task;
    }
}

Application_Start global.asax


GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonFormatter());
GlobalConfiguration.Configuration.Formatters.Insert(1, new XMLFormatter());

, , .

0

, rub:

  • MediaTypeFormatter, System.IO.Stream, HTTP-;
  • IFormatterLogger.OnError(string,Exception), - "" ( ), .

So, if you want to see and respond to (or register) the request that caused the error, you will need to implement and register your own MediaTypeFormatter, perform your own parsing / de-serialization and process it according to your own protocols (in addition to WebApi) .

0
source

All Articles