In my program I am generating a custom HttpWebRequest
based off of the following JSON schema:
{
"Endpoint": "String",
"Method": "String",
"Headers": [
{
"Name": "String",
"Value": "String"
}
]
}
And the code below loops through each Header
and adds it to the HttpWebRequest
var request = (HttpWebRequest)WebRequest.Create(Endpoint);
foreach (var item in Headers)
{
request.Headers.Add(item.Name, item.Value);
}
This works for most custom headers, but I came across the problem of setting the ContentType
header. Since that specific header cannot be added in by the above method, I devised a way, using Reflection
to set the request
's ContentType
property.
public static void SetHeaderValue(this HttpWebRequest request, string headerName, string headerValue)
{
Type type = typeof(HttpWebRequest);
PropertyInfo prop = type.GetProperty(headerName);
if (prop != null)
{
prop.SetValue(request, headerValue);
}
}
My question is this: Is using Reflection
the best way to approach this, or even a safe way to approach solving this problem?
Aucun commentaire:
Enregistrer un commentaire