I have a very light weight REST API that I wrote that validates a user. I want to return the validation as a JSON object, which I can, but if there are missing arguments, I want to kick back an error with some information. Here is my controller
public class GraphAccessController : ApiController
{
private UserValidation _userValidation;
private UserPermissions _userPermissions;
string _application;
public GraphAccessController()
{
_userValidation = new UserValidation();
_userPermissions = new UserPermissions();
}
public object GetUserValidation(string application)
{
if (string.IsNullOrEmpty(application))
{
return StatusCode(HttpStatusCode.MethodNotAllowed);
//return new HttpResponseException(HttpStatusCode.MethodNotAllowed);
}
try
{
_application = application;
ValidateUser(WindowsIdentity.GetCurrent(), application);
return _userValidation;
}
catch (HttpResponseException e)
{
string error = e.ToString();
return StatusCode(HttpStatusCode.InternalServerError);
}
}....(other private calls for validation)
{
When the "application" is passed in, I get a nice JSON object back. However, when I am trying to return an error to the user while checking for IsNullOrEmpty, if I just call with PostMan:
return StatusCode(HttpStatusCode.MethodNotAllowed)
the status is set to "405 Method Not Allowed" but I would like to pass down some text to indicate why it failed. So I tried:
throw new HttpResponseException(HttpStatusCode.MethodNotAllowed);
and this just stops execution in my control. So I did a return instead of throw I get a status of 200 (indicating everything was fine) but the JSON header data:
{ "Response": { "Version": { "_Major": 1, "_Minor": 1, "_Build": -1, "_Revision": -1 }, "Content": null, "StatusCode": 405, "ReasonPhrase": "Method Not Allowed", "Headers": [], "RequestMessage": null, "IsSuccessStatusCode": false }, "Message": "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.", "Data": {}, "InnerException": null, "TargetSite": null, "StackTrace": null, "HelpLink": null, "Source": null, "HResult": -2146233088 }
As you can see from the code in the catch I am also trying to do the same type of thing. How do you return a StatusCode with corresponding information text to the caller so they can check the status and if it isn't 200, check the body for error text?
Thanks