在ServiceStack中使用IRestClient发出HEAD请求

时间:2012-12-27 18:02:15

标签: c# http servicestack httpverbs

上下文:我已经构建了一个处理'Profile'对象的REST服务。每个配置文件都必须具有唯一的名称。客户端为验证目的需要执行的操作之一是检查以确保具有给定名称的配置文件尚不存在。

我宁愿保持REST设计原则并使用给定名称向配置文件发出HEAD请求,而不是构建RPC样式的“ProfileExists”方法,然后根据配置文件是否已存在返回相应的响应代码与否(分别为200,404),无需回应。

遵循使用较新的ServiceStack API的约定,我已经设置了一个接受Head请求的方法,并使用Fiddler成功测试了两个案例:

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 个答案:

答案 0 :(得分: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 +)上提供。