如何从Catch块返回错误消息。 现在回来是空的

我的ApiKeyvalidation示例代码如下(我使用的是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); } } } } 

这里的问题是Catch块语句。 我只是想向用户发送自定义错误消息。 但没有发送任何东西。 它显示一个空白屏幕

但是,下面的语句运行良好,并正确发送validation错误消息:

 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); } 

有什么我做错了吗?

我在完全相同的情况下遇到了同样的问题。 但是,在这种情况下,您需要返回响应中的某些内容才能显示,而不是真正抛出exception。 基于此,我会将您的代码更改为以下内容:

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

因此,通过此更改,您现在将返回您的响应,其内容将显示在空白屏幕的位置。