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。 –
是的,我在找。如果有東西我會在這裏發佈。 –