修改WebApi DelegatingHandler中的Request.Content

时间:2014-12-06 15:54:20

标签: asp.net-web-api httpmodule

我需要修改请求的内容以替换一些字符(因为一些unicode问题)。以前(在ASP.NET MVC中)我使用 HttpModules 执行此操作,但在 WebApi 中,似乎我应该 DelegatingHandler ,但它完全不同。< / p>

现在我想知道如何在SendAsync方法中修改request.Content。我需要这样的东西:

  protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var s = await request.Content.ReadAsStringAsync();
    // do some modification on "s"
    s= s.replace("x","y");

    request.Content = new StringContent(s);

    var response = await base.SendAsync(request, cancellationToken);

    return response;
}

在上面的代码中,我想我应该检查请求的内容类型,然后决定要做什么。如果是,我应该做哪些检查?

1 个答案:

答案 0 :(得分:7)

我在SendAsync方法中执行了以下操作。虽然它不是一个全面的解决方案,但它的确有效! :

    //first : correct the URI (querysting data) first
    request.RequestUri = new Uri(Correcr(request.RequestUri.ToString()));

    var contentType = request.Content.Headers.ContentType;

    if (contentType != null)
    {
        if (contentType.MediaType == "application/x-www-form-urlencoded")//post,put,... & other non-json requests
        {
            var formData = await request.Content.ReadAsFormDataAsync();
            request.Content = new FormUrlEncodedContent(Correct(formData));
        }
        else if (contentType.MediaType == "multipart/form-data")//file upload , so ignre it
        {
            var formData = await request.Content.ReadAsFormDataAsync();
            request.Content = new FormUrlEncodedContent(Correct(formData));
        }
        else if (contentType.MediaType == "application/json")//json request
        {
            var oldHeaders = request.Content.Headers;
            var formData = await request.Content.ReadAsStringAsync();
            request.Content = new StringContent(Correct(formData));
            ReplaceHeaders(request.Content.Headers, oldHeaders);
        }
        else
            throw new Exception("Implement It!");
    }

    return await base.SendAsync(request, cancellationToken);

和这个辅助函数:

   private void ReplaceHeaders(HttpContentHeaders currentHeaders, HttpContentHeaders oldHeaders)
    {
        currentHeaders.Clear();
        foreach (var item in oldHeaders)
            currentHeaders.Add(item.Key, item.Value);
    }