4
我ApiKey验证的示例代码如下(我使用MVC4网页API RC)给出:如何从Catch块返回错误消息。现在空返回
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);
}
有什么,我做错了。
感谢Paige Cook,我现在可以获取StringContent“带api键的用户无效”而不是空白屏幕:-)。但另一个关心的问题是,我不想使用纯文本,而是想以当前格式化程序的格式(如xml或json)来获取结果。为此,我需要指定response.Content = new Error {Message =“如果没有密钥,则无法使用API。” }。此代码不起作用,并且是编译错误。如何在这里写代码行? –
不幸的是,我不知道该怎么做。有一种方法可以确定请求的MediaType并将消息格式化为相同的MediaType。 –
是的,我在找。如果有东西我会在这里发布。 –