Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contract.Requires for validations in web api

I am developing MVC5 / Web API based application. In some articles I have read use Contract.Requires (part of the System.Diagnostics.Contracts namespace) for validating the incoming data.

Is this the correct way of validating the incoming data? Also I am not able to debug the Contract.Requires line as 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.Requires and where to avoid?

like image 625
Neha Jain Avatar asked Feb 09 '23 13:02

Neha Jain


1 Answers

You certainly can use code contracts in your controllers but here are some downsides and reasons you may not need contracts.

  • Loss of error detail in API responses: A code contract failure will be returned to the client as an HTTP 500 internal server error, likely without details, which is not helpful to clients of the API. This is because the contract failure causes an exception to be thrown. You may prefer to throw an HttpResponseException with your own details instead, or custom tailor an HttpResponseMessage. In that case (unless you roll your own global exception handling) code contracts may not make sense.

  • Contract.Requires may be redundant: Consider how Web API may already be validating your parameters. For example, a missing parameter may result in an invalid route, so the request gets rejected and the method does not get called. Code contracts would be useless in this method.

  • Why do you need contracts? Code contracts are great for catching contract failures at compile-time. But unless your API clients are also .NET projects, then you can't take advantage of that feature. So consider what else you might need contracts to do and if that justifies their usage.

like image 190
Keith Avatar answered Feb 15 '23 10:02

Keith