【问题标题】:HttpContext.Current null in WebContentTypeMapper / GetMessageFormatForContentTypeWebContentTypeMapper / GetMessageFormatForContentType 中的 HttpContext.Current null
【发布时间】:2019-11-08 08:38:22
【问题描述】:

我想写一个 WebContentTypeMapper 来返回 uri 路径上的 WebContentFormat 依赖。

直到现在我使用HttpContext.Current.Request.PathInfo。 但如果有超过 64k 正文的大型 POST 请求,则 HttpContext.Current 为空。

我发现 HttpContext.Current 不打算在那里使用。但它适用于所有其他情况,即请求只有一些 kb 小。

有没有其他方法可以在GetMessageFormatForContentType()中找出当前请求的路径?

public class RawContentTypeMapper : WebContentTypeMapper
{
    public override WebContentFormat GetMessageFormatForContentType(string contentType)
    {
        string pathInfo;
        try
        {
            pathInfo = HttpContext.Current.Request.PathInfo;
        }
        catch (NullReferenceException e)
        {
            // This happens for large POST requests
            pathInfo = ...please help!
        }
        switch (pathInfo)
        {
            case "/abc/path1":
            case "/abc/path2":
                return WebContentFormat.Raw;
            default:
                return WebContentFormat.Default; // No change to default behavior
        }
    }
}

【问题讨论】:

  • 你有没有试过扩展IIS manager->Configuration editor->system.webServer/serverRuntime/uploadReadAheadSize的值?因为这个值的限制是46k左右
  • 我不知道。它的默认值为 49152。

标签: c# web-services iis


【解决方案1】:

我现在有一个解决方案。包括几个变化:

我将RawContentTypeMapper 更改为始终返回WebContentFormat.Raw

Web.config:

  • 添加了使用RawContentTypeMapper 的绑定副本并删除了contentTypeMapper 属性。所以它使用默认映射器。

  • 通过使用 RawContentTypeMapper 的绑定向每个地址(“abc/path1”...)添加了一个端点。

  • 使用默认绑定将端点添加到基地址“abc”。

IMySourceCode.cs:MySourceCode.cs:

UriTemplate = "" 创建了一个新的OperationContract。在那里,我检查了 HttpContext.Current.Request.PathInfo 中的“abc/path1/”、“abc/path2/”...并调用原始的 OperationContract 方法。

为此,所有 OperationContract 必须具有相同的签名(此处为 void MyMethod(Stream data))。

添加 Global.asax 将路径“abc/path1”重写为“abc/path1/”...:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var pathInfo = HttpContext.Current.Request.PathInfo.ToLowerInvariant();
        if (pathInfo.StartsWith("/abc/"))
        {
            foreach (var s in new[] { "/abc/path1", "/abc/path2" })
            {
                if (pathInfo == s)
                {
                    var rawUrl = HttpContext.Current.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
                    HttpContext.Current.RewritePath($"{rawUrl}/");
                    break;
                }
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多