Contract.Requires for web api validation

I am developing an application based on the MVC5 / Web API. In some articles that I read, use Contract.Requires(part of the namespace System.Diagnostics.Contracts) to validate incoming data.

Is this the right way to validate incoming data? Also, I cannot debug a line Contract.Requires, since the debugger always bypasses this line. I am using Visual Studio 2013.

    public async Task<UserInfo> Put(
        [FromBody] UserInfo userInfo) {
        Contract.Requires(userInfo != null);
        ..............
     }

Can someone explain when to use Contract.Requiresand where to avoid it?

+4
source share
3 answers

, , , .

  • API: HTTP 500, , , API. , . HttpResponseException custom . ( ) .

  • . : , -API . , , . .

  • ? . API .NET-, . , , .

+3

?

HttpResponseMessage api-:

[HttpPost]
    public HttpResponseMessage Put(UserInfo userInfo) {
     if(ModelState.IsValid)
    {
     // your code
    return Request.CreateResponse(HttpStatusCode.OK);
    }
    else
    {
    return Request.CreateResponse(HttpStatusCode.BadRequest, new { msg = "invalid data" });
    }
    }

:

  [HttpPost]
        public async Task<ActionResult> Put(UserInfo userInfo) {
         if(ModelState.IsValid)
        {
         // your code
        return Request.CreateResponse(HttpStatusCode.OK);
        }
        else
        {
        return Request.CreateResponse(HttpStatusCode.BadRequest, new { msg = "invalid data" });
        }
        }
+3

Web.Api, , .

Code Contracts (, -). , - , ApiController - (, ).

, HTTP 500, , , Code Contracts Web.Api(HttpStatusExceptionFilterAttribute). HTTP ( ) .

Using these two functions, you clean and optimize your code, providing the client with friendly and meaningful error information, while maintaining complete error information for internal troubleshooting.

You can take a look at this article, which explains this a bit further: Using CodeContracts with OData controllers and Web.Api exception filters

hope this helps

Regards, Ronald

+2
source

Source: https://habr.com/ru/post/1616267/


All Articles