2012-12-27 24 views
2

上下文:我構建了一個處理「Profile」對象的REST服務。每個配置文件都必須具有唯一的名稱。客戶需要爲驗證目的執行的操作之一是檢查以確保具有給定名稱的配置文件不存在。使用ServiceStack中的IRestClient發出HEAD請求

與其構建RPC樣式的「ProfileExists」方法,我更願意保留在REST設計原則中,並使用給定名稱向配置文件發出HEAD請求,然後返回相應的響應代碼,具體取決於配置文件是否已是否存在(分別爲200,404),不需要響應主體。

在與新ServiceStack API的約定,我已經設置了接受HEAD請求的方法和成功地測試它使用招兩種情況:

public object Head(GetProfile request) 
{ 
    ValidateRequest(request); 

    HttpStatusCode responseCode; 

    using (var scope = new UnitOfWorkScope()) 
    { 
     responseCode = _profileService.ProfileExists(request.Name) ? HttpStatusCode.OK : HttpStatusCode.NotFound; 

     scope.Commit(); 
    } 

    return new HttpResult { StatusCode = responseCode }; 
} 

麻煩的是在客戶端。證明通過ServiceStack的IRestClient接口發出HEAD請求非常困難。雖然有Get,Post,Put和Delete方法,但Head沒有方法。從那裏,我以爲我可以用CustomMethod明確指定HEAD動詞作爲參數:

public bool ProfileExists(string profileName) 
{ 
    try 
    { 
     var response = _restClient.CustomMethod<IHttpResult>(HttpMethods.Head, new GetProfile { Name = profileName }); 

     return response.StatusCode == HttpStatusCode.OK; 
    } 
    catch (WebServiceException ex) 
    { 
     if (ex.StatusCode == 404) 
      return false; 
    } 

    // Return false for any other reason right now. 
    return false; 
} 

然而,底層實現(ServiceClientBase)驗證HttpVerb參數時拋出異常:

if (HttpMethods.AllVerbs.Contains(httpVerb.ToUpper())) 
       throw new NotSupportedException("Unknown HTTP Method is not supported: " + httpVerb); 

的集HttpMethods.AllVerbs包含RFC 2616等所有常用動詞。除非這種行爲是一個錯誤,否則爲任何已知的HTTP動詞拋出異常表明作者的CustomMethod意圖不包括能夠發出對已知HTTP動詞的請求。

這使我對我的問題:如何在ServiceStack客戶端發出HEAD請求?

回答

1

這是一個錯誤:

if (HttpMethods.AllVerbs.Contains(httpVerb.ToUpper())) 
    throw new NotSupportedException("Unknown HTTP Method is not supported: " + httpVerb); 

那我剛剛fixed in this commit。此修復將在本週末發佈的ServiceStack(v3.9.33 +)的下一個版本中提供。

+0

非常好。這現在更有意義了。感謝您添加提交! –