ServiceStack-服务网关中的头请求

问题描述 投票:1回答:1

我有一个验证器,必须检查另一个实体的存在。我希望能够使用HEAD方法调用ServiceGateway来检查404/200的状态。 。

目前,我在做恶作剧。我正在发出常规的GET请求,并被try / catch包围。但这大量的404污染了我的日志。另外,有时,我必须检查某些实体的不存在。所以我的日志显示404s错误,但这是预期的。

我可以实现另一个DTO来进行检查,但是我更喜欢使用现有的HTTP约定

我尝试使用ServiceGateway /自定义BasicRequest

但是我有两个问题

我无法访问ServiceGateway IResponse(Gateway.Send()。Response.StatusCode)。

我无法将动词设置为HEAD(InProcess仅支持GET,POST,DELETE,PUT,OPTIONS,PATCH)

而且,通常也没有IHead接口/ HEAD支持


我的问题是:如何在内部使用服务网关发出HEAD请求,以检查是否存在(或缺少)其他实体? -通过InProcess,Grpc,Json等...

此外,这对于访问内置的版本控制(Etags,...)也很有用


[Route("/api/other-entity/{Id}", "GET,HEAD")]
public class GetOtherEntity : IReturn<OtherEntityDto>, IGet
{
  public Guid Id {get; set;}
}


public class OtherEntityService : Service {

  public async Task<object> Get(GetOtherEntity request){
    return (await _repository.Get(request.Id)).ToDto();
  }

  // This doesn't get called
  public async Task Head(GetOtherEntity request){
    var exists = await _repository.Exists(request.Id);
    Response.StatusCode = exists ? (int)HttpStatusCode.OK : (int)HttpStatusCode.NotFound;
  }

  // This either
  public async Task Any(GetOtherEntity request){
    var exists = await _repository.Exists(request.Id);
    Response.StatusCode = exists ? (int)HttpStatusCode.OK : (int)HttpStatusCode.NotFound;
  }


}

public class CreateMyEntityValidator: AbstractValidator<CreateMyEntity>{

  public CreateMyEntityValidator(){


    // This rule ensures that the OtherId references an existing OtherEntity

    RuleFor(e => e.OtherId).MustAsync(async (entity, id, cancellationToken) => {

      var query = new GetOtherEntity(){ Id = id };
      var request = new BasicRequest(query , RequestAttributes.HttpHead);

      // This doesn't call the OtherService.Head nor the OtherService.Any
      // Actually my logs show that this registers a a POST request ?
      var response = await HostContext.AppHost.GetServiceGateway(Request).SendAsync(request);

      // And how could I get the response.StatusCode from here ? 
      return response.StatusCode == (int)HttpStatusCode.OK;

    })


  }

}

servicestack
1个回答
0
投票

您无法在ServiceStack Services中实现HEAD请求。

您可以在ServiceStack之前通过在Pre Request Filters中进行拦截和短路来处理它们,例如:

RawHttpHandlers.Add(httpReq =>
  httpReq.HttpMethod == HttpMethods.Head
    ? new CustomActionHandler(
    (httpReq, httpRes) =>
    {
        // handle request and return desired response
        httpRes.EndRequest(); //short-circuit request
    });
    : null);

但是很少有HTTP客户端将对HEAD请求提供本机支持,通常,您只是试图获取资源,如果目标资源不存在,则会抛出404 Exception。

如果需要通常检查资源是否存在而不返回资源,则可以通过实现一个批处理服务来实现更多实用性,该服务接受一批IDS或URN,并返回存在的字典或ID列表。

© www.soinside.com 2019 - 2024. All rights reserved.