How to migrate from HttpRequestMessage.Properties to HttpRequestMessage.Options
Asked Answered
T

3

13

After upgrading to net5 I'm getting obsoletion warning: [CS0618] 'HttpRequestMessage.Properties' is obsolete: 'Use Options instead.' however there seems to be no migration guide.

I.e. there's following code

httpRequestMessage.Properties.Add(Key, Value);

How exactly it should be migrated? Is

httpRequestMessage.Options.Set(new HttpRequestOptionsKey<TValue>(Key), Value);

correct?

Tenedos answered 6/7, 2021 at 12:53 Comment(4)
The Options property, of type HttpRequestOptions, is an IDictionary<string, object>, as the Properties property...Abettor
... so, e.g., httpRequestMessage.Options.Set<string>(new HttpRequestOptionsKey<string>("100"), "10");, httpRequestMessage.Options.Set<float>(new HttpRequestOptionsKey<float>("100"), 10.0f); etc.Abettor
But this dictionary is private, so you cannot use it like dictionary. For some reason the added this weird api with HtppRequestOptionsKey and I want to know why they did so.Tenedos
Issue 34168 - Configuring request options in Browser WebAssemblyAbettor
J
12

I struggled with the same thing and I found the solution. Here is how you should use the new Options property.

Instead of request.Properties.Add("foo", true);
Write: request.Options.Set(new HttpRequestOptionsKey<bool>("foo"), true);

To read the key from response:
response.RequestMessage.Options.TryGetValue(new HttpRequestOptionsKey<bool>("foo"), out bool foo);

To be honest, I don't know why they changed it. It's strange we need to create a new HttpRequestOptionsKey object for each property. But it is what it is.

Jarlathus answered 20/10, 2022 at 11:28 Comment(1)
You can see in issue linked by Jimi that it's related to browser and webassembly. I just don't understand why they didn't add extension method which would handle it.Tenedos
G
-1

You could switch on type - here's an example from attempting to clone an existing message:

foreach (var opt in httpRequestMessage.Options)
{
    switch (opt.Value)
    {
        case string s:
            clone.Options.Set<string>(new HttpRequestOptionsKey<string>(opt.Key), s);
            break;
        default:
            throw new InvalidOperationException("Can't deal with non-string message options ... yet.");    
    }
}
Groningen answered 20/1, 2022 at 14:52 Comment(2)
This is question about how to migrate code from obsoleted api, rather than copy options between cloned messages.Tenedos
This code is useful for migration as wellUnsuspecting
V
-1

maybe this could give some idea how to get the value from HttpRequestMessage.Options

request.Options.TryGetValue(new HttpRequestOptionsKey<DefaultHttpContext>("HttpContext"), out var HttpContextValue);

Vallecula answered 28/5 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.