我正在編寫一個WCF webapi應用程序,並且需要檢查一個電子郵件地址是否被採用。在嘗試PUT
之前,這需要客戶端代碼可以執行的查詢。WCF WebApi,處理IsThisTaken查詢的正確方法是什麼?
所以,我想要做的是使用HEAD
與HTTP狀態代碼結合使用。我有點不確定如何去做,因爲這是一個簡單的是/否回答,這是必需的。所以,我用HttpResponseExceptions
來返回相關的狀態碼。
[WebInvoke(Method = "HEAD", UriTemplate = "{email}")]
[RequireAuthorisation]
public void IsEmailAddressTaken(string email)
{
if (!Regex.IsMatch(email, Regexes.EmailPattern))
{
throw new RestValidationFailureException("email", "invalid email address");
}
if (_repository.IsEmailAddressTaken(email))
{
throw new HttpResponseException(HttpStatusCode.OK);
}
throw new HttpResponseException(HttpStatusCode.NoContent);
}
這只是沒有「氣味」對我。
首先,我要以正確的方式進行這種「是/否」操作嗎?
其次,有沒有辦法只是返回相關的狀態碼,而不必訴諸異常?
回答第二個問題
回答我的第二個問題是隻是有方法返回一個HttpResponseMessage
[WebInvoke(Method = "HEAD", UriTemplate = "{email}")]
[RequireAuthorisation]
public HttpResponseMessage DoesResourceExist(string email)
{
if (!Regex.IsMatch(email, Regexes.EmailPattern))
{
return new RestValidationFailure("email", "invalid email address");
}
if (_repository.IsEmailAddressTaken(email))
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
謝謝。我剛剛到達那裏:)我想我可能會添加我的解決方案到我的問題,因爲你輸入這個答案。 – 2012-01-18 12:12:39