This week I'll be running a series covering fixes for WCF that may be hard to find and explaining the details behind each problem.

This next fix is actually to add a new feature when writing a UserNamePasswordValidator.

A UserNamePasswordValidator gives you a callback method called Validate that takes user name and password parameters supplied by the client. If you decide that the user name and password don't pass validation, then you can throw an exception out of the Validate method to reject the client's message. When using the HTTP transport, the error message sent back after the UserNamePasswordValidator has a status code 403 Forbidden.

After installing this fix you're able to customize the status code that is sent back. To do so, add an object to the exception's data collection with the key HttpStatusCode. The value has to be an instance of the HttpStatusCode class or else it will be ignored. The type of the exception doesn't matter.

For example, to set the status code to 401 Unauthorized, here is the code you would write before throwing the exception.

exception.Data["HttpStatusCode"] = HttpStatusCode.Unauthorized;

This fix is available for download from KB article 957911.