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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With