Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to remove prefixes from ModelState keys?
    primarykey
    data
    text
    <p>For example, there is a Web Api action method:</p> <pre><code>public HttpMessageResponse Post(UserDto userDto) { if (!this.ModelState.IsValid) { return this.Request.CreateErrorResponse( HttpStatusCode.BadRequest, this.ModelState); } // ... } </code></pre> <p>A client sends the following request:</p> <pre><code>HTTP POST: /api/user { "username": "me", "password": "Pa$sw0rd" } </code></pre> <p>And gets the response:</p> <pre><code>HTTP 201/Created: { "message": "Your request is invalid.", "modelState": { "userDto.Password": "Your password is too strong." } } </code></pre> <p>By default the action method exposes implementation details by prefixing model errors with an argument name used inside the action method. What if client apps will hardcode this prefix name when cleaning up model errors, then server-side code changes (for example you replaced <code>Post(UserDto userDto)</code> signature with <code>Post(UserDto dto)</code>) and all client apps stop working.</p> <p>That's why you need to make sure this prefix is removed on the server-side. The question is, how to do it properly, without complicating things. For example you can create a custom serializer and remove these prefixes during serialization. But in order to do so, you need to know the name of the model argument and the calling code may look something like this:</p> <pre><code>public HttpMessageResponse Post(UserDto userDto) { if (!this.ModelState.IsValid) { return this.Request.CreateCustomErrorResponse( HttpStatusCode.BadRequest, this.ModelState, modelName: "userDto"); } // ... } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload