Freigeben über


Fix to Allow Customizing the Status Code when Validation Fails

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.

Comments

  • Anonymous
    February 10, 2010
    Hi Nicholas, We've been having this problem with our self-hosted WCF REST service. Oddly, your fix above works on a vanilla .NET 3.5 SP1 install. Any idea why this is the case? Also, even with this fix in place the behaviour of WCF's authentication is still broken. Because even if you specify it to return a 401 Unauthorized response, it won't include a "WWW-Authenticate" header. So the web browser won't re-prompt the user to enter their credentials. Unfortunately, when self-hosting, it is not possible to manually insert this header because System.Net.HttpListener forbids it from being added manually. Surely WCF should override this behaviour of HttpListener? Our MS Connect report is at https://connect.microsoft.com/VisualStudio/feedback/details/531787/self-hosted-wcf-rest-with-http-basic-authentication#tabs Thanks.

  • Anonymous
    February 14, 2010
    Hi Nathan, The fixes are generally added to many different servicing releases including things like the Windows compatibility updates.  You might get this through Windows update or another source even if you haven't installed the fix directly.  If depending on the fix in a product you should require customers to get it explicitly in case they haven't had the same updates installed.