c# - 在 ServiceStack 中使用 IRestClient 发出 HEAD 请求

标签 c# http servicestack http-verbs

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

与其构建 RPC 风格的“ProfileExists”方法,我更愿意遵循 REST 设计原则并向具有给定名称的配置文件发出 HEAD 请求,然后根据配置文件是否已存在返回适当的响应代码或不是(分别为 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 接口(interface)发出 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 请求?

最佳答案

这是一个错误:

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

我刚刚fixed in this commit .此修复将在本周末发布的下一个 ServiceStack 版本 (v3.9.33+) 中可用。

关于c# - 在 ServiceStack 中使用 IRestClient 发出 HEAD 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14059085/

相关文章:

c# - 从 XML 数据反序列化数组(在 ServiceStack 中)

c# - 如何使用 ServiceStack.Text 在 header 中导入带有空格的 CSV 文件

security - 网络抓取工具能否绕过良好的 throttle 保护?

ServiceStack 4 用户注册不起作用

C# Service Bus 多个监听器都收到相同的消息 (BrokeredMessage)

c# - 传递给方法时根据元素类型填充列表

javascript - 使用 POST 设置请求 header 内容类型

http - 通过代理的 rtsp over http

c# - 基类设置为派生类,无法调用派生类中的方法?

c# - 是否有用于将属性从一个类绑定(bind)到另一个类的开源 C# 库?