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

时间:2012-06-25 12:12:55

标签: c# asp.net-web-api

下面给出了我的ApiKey验证示例代码(我使用的是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块语句。我只是想向用户发送自定义错误消息。但没有发送任何东西。它显示一个空白屏幕

但是,以下声明运行良好并正确发送验证错误消息:

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

我做错了什么。

1 个答案:

答案 0 :(得分:13)

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

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

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