Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite HttpRequestMessage call to support <T>

I found a useful class that makes Web API calls with JSON serialize/deserialize support of type T. You can view the entire class/article here. I think I could get a lot of use out of this class and would like to try it. There is one error left that I can't figure out how to handle. It's in the following routine:

protected HttpRequestMessage GetHttpRequestMessage<T>(T data)
{
    MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/json");
    JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
    jsonSerializerSettings.Converters.Add(new IsoDateTimeConverter());

    JsonNetFormatter jsonFormatter = new JsonNetFormatter(jsonSerializerSettings);

    HttpRequestMessage requestMessage = new HttpRequestMessage<T>(data, mediaType, new MediaTypeFormatter[] { jsonFormatter });

    return requestMessage;
}

The error I am getting is:

Error   3   The non-generic type 'System.Net.Http.HttpRequestMessage' 
cannot be used with type arguments.

Where HttpRequestMessage<T> is underlined with a red squiggly.

How would I rewrite this routine/line of code in a way that will not break the generic usefulness of this class?

like image 966
rwkiii Avatar asked Dec 05 '25 05:12

rwkiii


1 Answers

That article is out of date; it is referencing the BETA version of Web API. The generic HttpRequestMessage<T> class was removed in the released version as explained here. Instead you should use the PostAsJsonAsync<T> extension method. Here is a more up-to-date tutorial that should give you what you need.

like image 73
Brian Rogers Avatar answered Dec 07 '25 15:12

Brian Rogers