4

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

有什么我做错了吗。

4

1 回答 1

13

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

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

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

于 2012-06-25T14:20:49.563 回答