How to return an error message from a catch block. Now empty empty returns

My ApiKey verification code example is below (I am using MVC4 web api RC):

public class ApiKeyFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext context) { //read api key from query string string querystring = context.Request.RequestUri.Query; string apikey = HttpUtility.ParseQueryString(querystring).Get("apikey"); //if no api key supplied, send out validation message if (string.IsNullOrWhiteSpace(apikey)) { var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." }); throw new HttpResponseException(response); } else { try { GetUser(decodedString); //error occurred here } catch (Exception) { var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "User with api key is not valid" }); throw new HttpResponseException(response); } } } } 

The problem here is the catch block expression. I just wanted to send a custom error message to the user. But nothing is sent. It displays a blank screen.

However, the expression below works well and sends a validation error message correctly:

 if (string.IsNullOrWhiteSpace(apikey)) { var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." }); throw new HttpResponseException(response); } 

Is there something I'm doing wrong.

+4
source share
1 answer

I had the same problem in the same scenario. However, in this case, you need to return some content in the response that will be shown, and not throw an exception. Therefore, based on this, I would change your code to the following:

  catch (Exception) { var response = context.Request.CreateResponse(httpStatusCode.Unauthorized); response.Content = new StringContent("User with api key is not valid"); context.Response = response; } 

So, with this change, you are now returning your answer, with content that will be displayed instead of a blank screen.

+12
source

All Articles