FROM Http Header 不包括在内,除非它是一个有效的电子邮件地址

FROM Http Header not included unless it's a valid email address

我正在使用 Advanced Rest Client Chrome extension to test a request to a Web API 2 endpoint. I'm trying to include a value in the "From" header but the value is null when it is not a valid email address. By reading the spec,看起来它应该只是一个有效的电子邮件地址,而不是必须。这是因为 Web API、Chrome、扩展还是其他原因导致的?

在您对 Fiddler 看到 header 发表评论后,我很好奇,所以我做了一些测试。这是我的控制器代码:

public class FromController : ApiController
{
    [Route("api/from")]
    public dynamic Get()
    {
        string from1 = null;
        string from2 = null;
        string from3 = null;

        from1 = this.Request.Headers.From;

        IEnumerable<string> headers;
        if (this.Request.Headers.TryGetValues("From", out headers))
        {
            from2 = headers.FirstOrDefault();
        }

        if (HttpContext.Current.Request.Headers.AllKeys.Contains("From"))
        {
            from3 = HttpContext.Current.Request.Headers["From"];
        }

        var output = new
        {
            From1 = from1,
            From2 = from2,
            From3 = from3
        };

        return output;
    }
}

测试 1:发送 e@test.com 作为发件人 header 输出:

{
    "From1": "e@test.com",
    "From2": "e@test.com",
    "From3": "e@test.com"
}

一切如预期。

测试 2:发送 junk 作为 From header 输出:

{
    "From1": null,
    "From2": "junk",
    "From3": "junk"
}

这表明您发现 header 为空,但您可以通过其他方法获得它。

内部是 运行 对值的一些解析。该值存储在无效容器中,因此直接请求它会导致 null。通过 TryGetValue 询问,它会忽略任何 "helpful" 解析,因此您将获得值。

我添加旧的 HttpContext.Current.Request 只是为了看看,因为这是更原始的形式,但我会避免在生产中使用它,并尝试在任何情况下坚持使用 this.Request控制器。我喜欢使用 HttpContext.Current.Request.SaveAs(fileName, true) 来查看实际的原始请求是什么。我首先这样做并看到了 header 所以我知道它必须以某种方式访问​​。