4
내 샘플 코드는 (내가 MVC4 웹 API를 RC를 사용하고 있습니다) 아래에 주어진다 반환됩니다Catch 블록에서 오류 메시지를 반환하는 방법. 지금 빈은 apiKey에 검증의
여기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);
}
내가 잘못하고 있어요 있나요.
고마워요 페이지 쿡, 이제 빈 화면 대신 "API 키가있는 사용자가 유효하지 않습니다."라는 StringContent를 얻을 수 있습니다. 그러나 또 다른 관심사는 일반 텍스트 대신 xml이나 json과 같은 현재 포맷터 형식으로 결과를 얻고 싶다는 것입니다. 이것을 위해 response.Content = new Error를 할당해야합니다. {Message = "키없이 API를 사용할 수 없습니다." }. 이 코드는 작동하지 않으며 컴파일 오류입니다. 여기에 코드 줄을 쓰는 방법은 무엇입니까? –
불행히도, 어떻게 해야할지 모르겠다. 요청의 MediaType을 결정하고 동일한 MediaType에 메시지를 형식화하는 방법이있을 수 있습니다. –
예, 찾고 있습니다. 뭔가가 있으면 여기에 게시 할 것입니다. –