delegatingHandler(webapi)等效于servicestack

时间:2013-04-08 21:09:00

标签: asp.net-web-api servicestack

我正在尝试从asp.net mvc4 webapi框架迁移到servicestack框架。我在webapi中有一个delegatingHandler,它在servicestack中等同于什么?

这是我将验证我的请求并返回自定义响应的地方。

MY DELEGATINGHANDLER

public class xyzDH : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        int maxLengthAllowed = 200;
        long? contentLen = request.Content.Headers.ContentLength; 
        if (contentLen > maxLengthAllowed)
        {
            var defaultResponse = ResponseHelper.GetBaseResponse("Content Lenght Issue", true, UploadLogSizeIssue);
            return Task<HttpResponseMessage>.Factory.StartNew(() =>
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(defaultResponse.ToString(), Encoding.UTF8, "message/http")
                    };
                return response;
            });
        }

        return base.SendAsync(request, cancellationToken);
    }
}

1 个答案:

答案 0 :(得分:5)

最好先浏览一下ServiceStack's simple Architecture,以便全面了解ServiceStack的组合方式。

Custom Hooks, Filters and Extensibility points

ServiceStack允许在Order of Operations wiki page中标识许多自定义挂钩和可扩展点。您可以使用自定义Filter AttributeGlobal Filters来执行此操作,这样您就可以直接写入响应,之后您可以调用httpResponse.EndServiceStackRequest()扩展方法来表示不再需要进行处理请求。

Validators

由于您在请求验证的上下文中询问,您应该查看ServiceStack's built-in validation,它允许使用内置的FluentValidation进行声明性验证。

Error Handling

在很多情况下,只需抛出正常的C#异常即可。 ServiceStack提供了一个很好的故事,包括序列化服务客户端中的异常。阅读Error Handling wiki以了解自定义异常处理的不同方法。

使用全局请求过滤器

这是您可以使用ServiceStack Global Request Filter重写WebApi委派处理程序的方法:

this.RequestFilters.Add((httpReq, httpResp, requestDto) =>
{
    int maxLengthAllowed = 200;
    if (httpReq.ContentLength > maxLengthAllowed)
    {
        //httpRes.StatusCode = 200; //No-op, not needed since its the default
        //Guess it could also be "message/http" but never heard of it
        httpRes.ContentType = "text/plain"; 
        httpRes.Write("Content Length Issue"); //Whatever you want in body
        httpRes.EndServiceStackRequest(); //No more processing for this request
    }
});

警告:建议不要为无效的HTTP请求返回200 OK,如上所示。如果请求无效,则应该是400 BadRequest错误,这是ServiceStack将在throw a C# Exception inheriting ArgumentException时自动写入的错误。

相关问题