คำตอบก่อนหน้านี้ทั้งหมดอธิบายถึงปัญหาโดยไม่ต้องให้คำตอบ นี่คือวิธีการขยายที่แก้ปัญหาโดยให้คุณตั้งค่าส่วนหัวผ่านชื่อสตริง
การใช้
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.SetRawHeader("content-type", "application/json");
คลาสส่วนขยาย
public static class HttpWebRequestExtensions
{
    static string[] RestrictedHeaders = new string[] {
            "Accept",
            "Connection",
            "Content-Length",
            "Content-Type",
            "Date",
            "Expect",
            "Host",
            "If-Modified-Since",
            "Keep-Alive",
            "Proxy-Connection",
            "Range",
            "Referer",
            "Transfer-Encoding",
            "User-Agent"
    };
    static Dictionary<string, PropertyInfo> HeaderProperties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
    static HttpWebRequestExtensions()
    {
        Type type = typeof(HttpWebRequest);
        foreach (string header in RestrictedHeaders)
        {
            string propertyName = header.Replace("-", "");
            PropertyInfo headerProperty = type.GetProperty(propertyName);
            HeaderProperties[header] = headerProperty;
        }
    }
    public static void SetRawHeader(this HttpWebRequest request, string name, string value)
    {
        if (HeaderProperties.ContainsKey(name))
        {
            PropertyInfo property = HeaderProperties[name];
            if (property.PropertyType == typeof(DateTime))
                property.SetValue(request, DateTime.Parse(value), null);
            else if (property.PropertyType == typeof(bool))
                property.SetValue(request, Boolean.Parse(value), null);
            else if (property.PropertyType == typeof(long))
                property.SetValue(request, Int64.Parse(value), null);
            else
                property.SetValue(request, value, null);
        }
        else
        {
            request.Headers[name] = value;
        }
    }
}
สถานการณ์
ฉันเขียนกระดาษห่อหุ้มHttpWebRequestและไม่ต้องการเปิดเผยส่วนหัวที่ถูก จำกัด ทั้ง 13 รายการเป็นคุณสมบัติในกระดาษห่อหุ้มของฉัน แต่ฉันต้องการใช้ไฟล์Dictionary<string, string>.
อีกตัวอย่างหนึ่งคือพร็อกซี HTTP ที่คุณต้องใช้ส่วนหัวในคำขอและส่งต่อไปยังผู้รับ 
มีสถานการณ์อื่น ๆ อีกมากมายที่ไม่สามารถใช้คุณสมบัติได้จริงหรือเป็นไปได้ การบังคับให้ผู้ใช้ตั้งค่าส่วนหัวผ่านพร็อพเพอร์ตี้เป็นการออกแบบที่ไม่ยืดหยุ่นซึ่งเป็นเหตุให้ต้องมีการสะท้อนกลับ ด้านบนคือการสะท้อนกลับเป็นนามธรรมออกไปมันยังเร็ว (.001 วินาทีในการทดสอบของฉัน) และวิธีการขยายให้ความรู้สึกเป็นธรรมชาติ
หมายเหตุ
ชื่อส่วนหัวไม่คำนึงถึงตัวพิมพ์เล็กและใหญ่ตาม RFC, http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2