Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
tays revenge
Aug 29, 2009

raminasi posted:

The Ctrl-T search is way better than in vanilla.

That and the Shift+Alt+L

Adbot
ADBOT LOVES YOU

Nurbs
Aug 31, 2001

Three fries short of a happy meal...Whacko!
Someone mentioned NancyFx to me today, and I've read all their documentation and I'm just not seeing the value proposition vs. asp.net webapi. Yes Nancy looks a little less verbose, but I haven't run into enough problems where I see it's...flexibility or 'streamlined' framework as a substantial benefit

Am I missing some obvious use cases?

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Nurbs posted:

Someone mentioned NancyFx to me today, and I've read all their documentation and I'm just not seeing the value proposition vs. asp.net webapi. Yes Nancy looks a little less verbose, but I haven't run into enough problems where I see it's...flexibility or 'streamlined' framework as a substantial benefit

Am I missing some obvious use cases?

Having just taken a quick glance at it, it would be excellent for very quickly prototyping something but I'm kind of with you that I can't see how you'd be able to rely on it in a real world application - it would get very untidy very quick.

SixPabst
Oct 24, 2006

raminasi posted:

The Ctrl-T search is way better than in vanilla.

This and the context aware Alt-Enter are the main reason I keep using it.

NiceAaron
Oct 19, 2003

Devote your hearts to the cause~

a hot gujju bhabhi posted:

I use it primarily for its code style features, since I work a lot of inherited code and I like to try to bring it into line with good style while I work on it, having the highlighting from ReSharper is super handy for that.

Unrelated:

I'm used to ASP.NET MVCs handing of bundling and minification, where you could use a HtmlHelper to include the JavaScript and the internals would decide whether or not to render on script tag serving the minified concatenated JS, or render several tags serving each individual unminified file separately based on your environment. This was pretty useful because you essentially just threw your JS file paths into an array and let MVC handle the rest. It was all in the one place.

In ASP.NET Core MVC, they seem to have removed this in favour of using "environment" tags to render different script tags depending on the environment. The bundler ALWAYS bundles, and it's up to you to include either the bundled file or the individual files depending on the environment. This means every new file needs to be added to the bundle config, AND to the layout view. Is there a way to get the same behaviour as before?

I haven't done much with ASP.NET Core MVC yet, and I'm especially unfamiliar with the changes to bundling / minification, but I imagine it wouldn't be too hard to write a custom tag helper that reads the bundle config and does what you want. e.g. pass the output file name into the custom tag helper, and depending on the environment the custom tag helper decides to either render a single script tag for that output file, or parse the bundleconfig.json file to find the corresponding input files and render script tags for them.

Shy
Mar 20, 2010

Nurbs posted:

Someone mentioned NancyFx to me today, and I've read all their documentation and I'm just not seeing the value proposition vs. asp.net webapi. Yes Nancy looks a little less verbose, but I haven't run into enough problems where I see it's...flexibility or 'streamlined' framework as a substantial benefit

Am I missing some obvious use cases?

I'm pretty sure it appeared long time ago and asp.net propositions weren't there yet.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

NiceAaron posted:

I haven't done much with ASP.NET Core MVC yet, and I'm especially unfamiliar with the changes to bundling / minification, but I imagine it wouldn't be too hard to write a custom tag helper that reads the bundle config and does what you want. e.g. pass the output file name into the custom tag helper, and depending on the environment the custom tag helper decides to either render a single script tag for that output file, or parse the bundleconfig.json file to find the corresponding input files and render script tags for them.

Yeah you're quite right, I was hoping for a built in thing but rolling my own probably won't be too tricky if all else fails. Thanks for the suggestion.

Potassium Problems
Sep 28, 2001

Shy posted:

I'm pretty sure it appeared long time ago and asp.net propositions weren't there yet.

yeah IIRC Nancy's been around since 2010, as a .NET answer to Sinatra

Mr Shiny Pants
Nov 12, 2012
NancyFX is pretty nice, it has some structuring that you have to be aware of. But the guys who wrote it are really good.

Essential
Aug 14, 2003
Anyone know how I can authenticate an httpclient request when all I am passing in is an api key (key/value pair)? I have a bunch of code using Basic authentication and passing in a username/password combo, but in this case all I need to pass in is "api-key" and the key value.

I'm working with the following:
code:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "api-key", "keyvaluehere"))));
Edit: I got it, it's just a standard header, not an authentication header. Here it is:
code:
client.DefaultRequestHeaders.Add("api-key", "apikeygoeshere");

Essential fucked around with this message at 23:27 on May 17, 2018

reversefungi
Nov 27, 2003

Master of the high hat!
Anyone know of any extensions like these (basically Ctrl + D in VS Code) for Visual Studio 2012? https://marketplace.visualstudio.com/items?itemName=thomaswelen.SelectNextOccurrence

Little things like this are why I end up doing larger coding in VS code rather than Visual Studio...

B-Nasty
May 25, 2005

The Dark Wind posted:

Anyone know of any extensions like these (basically Ctrl + D in VS Code) for Visual Studio 2012? https://marketplace.visualstudio.com/items?itemName=thomaswelen.SelectNextOccurrence

Little things like this are why I end up doing larger coding in VS code rather than Visual Studio...

If you're forced to use the 6-year-old VS2012, I don't blame you for using VS Code instead.

Is there some issue with solution/project migration that's keeping you on '12, or is your employer just cheap as hell? VS has improved substantially since then, and it's worth paying for the newest version.

LongSack
Jan 17, 2003

Time for my annual “anyone know of a good print library” question. I’m talking about report oriented stuff, which is mostly FixedDocuments rather than FlowDocuments. Where I’ve done them, holy crap is it a pain in the rear end, throwing together grids, stackpanels, textboxes, etc. and having to track the y-values (“heights”) of the various controls for pagination.

Generally, if I can get away with it, I instead offer an option to export the data to excel (thanks EPPlus!) in the name of “flexibility” - here’s the data, do with it what you will.

I’d kill for a decent print library though.

underage at the vape shop
May 11, 2011

by Cyrano4747
E: I figured it out

underage at the vape shop fucked around with this message at 08:15 on May 19, 2018

Sindai
Jan 24, 2007
i want to achieve immortality through not dying
If your ElapsedTicks are smaller than Stopwatch.Frequency (in other words, if the test took less than a second) integer division will give you a 0 there. Just casting ElapsedTicks to a double should fix it. Or multiply by a billion before dividing.

Also, now that I check I think you're actually multiplying by 100 million.

underage at the vape shop
May 11, 2011

by Cyrano4747

Sindai posted:

If your ElapsedTicks are smaller than Stopwatch.Frequency (in other words, if the test took less than a second) integer division will give you a 0 there. Just casting ElapsedTicks to a double should fix it. Or multiply by a billion before dividing.

Also, now that I check I think you're actually multiplying by 100 million.

Yeah I made a mistake with data types like an idiot. And you were right, it was only 100 million

Sindai
Jan 24, 2007
i want to achieve immortality through not dying
To be honest I would have written it as 1000*1000*1000 because I don't trust myself to count past my fingers. :v:

underage at the vape shop
May 11, 2011

by Cyrano4747
Normally I write it like 1 000 000 000 then delete the spaces, but today I was feeling cocky.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

underage at the vape shop posted:

Normally I write it like 1 000 000 000 then delete the spaces, but today I was feeling cocky.

C# 7 has digit separators.

http://www.davidhayden.me/blog/csharp-7-underscore-as-digit-separator-in-numeric-literals

epswing
Nov 4, 2003

Soiled Meat

LongSack posted:

Time for my annual “anyone know of a good print library” question. I’m talking about report oriented stuff, which is mostly FixedDocuments rather than FlowDocuments. Where I’ve done them, holy crap is it a pain in the rear end, throwing together grids, stackpanels, textboxes, etc. and having to track the y-values (“heights”) of the various controls for pagination.

Generally, if I can get away with it, I instead offer an option to export the data to excel (thanks EPPlus!) in the name of “flexibility” - here’s the data, do with it what you will.

I’d kill for a decent print library though.

I feel your pain. I couldn't take the FixedDocument/FlowDocument madness anymore and wrote a text-based, fixed-width printing utility where you specify your column headers, widths, and alignment, and just write rows/cells in a loop. It re-prints headers on page-breaks too. It's not as "cool" as text that flows and wraps and all that, but it works well. Luckily my customers don't care if it's not flashy, they just want something that works and is simple. I've been meaning to open-source it (GitHub, Nuget, etc), but I keep reading horror stories from OSS maintainers.

epswing fucked around with this message at 18:42 on May 19, 2018

LongSack
Jan 17, 2003

epalm posted:

I feel your pain. I couldn't take the FixedDocument/FlowDocument madness anymore and wrote a text-based, fixed-width printing utility where you specify your column headers, widths, and alignment, and just write rows/cells in a loop. It re-prints headers on page-breaks too. It's not as "cool" as text that flows and wraps and all that, but it works well. Luckily my customers don't care if it's not flashy, they just want something that works and is simple. I've been meaning to open-source it (GitHub, Nuget, etc), but I keep reading horror stories from OSS maintainers.

That’s an interesting idea for stuff that’s truly tabular - pick a fixed-pitch font and go for it. That would solve about 90% of my issues, too, and would be fun to write. That leaves “the beast” - a character portfolio manager for authors. So much of the data is variable length, it really does require all the lower level controls and height tracking. I’d try to write something myself, but it seems rather daunting.

mystes
May 31, 2006

The easiest way to actually generate printable files nowadays is probably to use some sort of html to pdf conversion program or library, but this won't easily integrate into a desktop application as easily as it would with a web page.

underage at the vape shop
May 11, 2011

by Cyrano4747

this is huge

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

mystes posted:

The easiest way to actually generate printable files nowadays is probably to use some sort of html to pdf conversion program or library, but this won't easily integrate into a desktop application as easily as it would with a web page.

Use Razor templates, RazorLight to render them and HTML to PDF to print them. If HTML to PDF isn't getting the rendering quite right, use Chrome programmatically to render the page and print it.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
Any AutoMapper geniuses here?

I need to know if there's a way to configure a mapping such that it uses one or another property as the source object for all mappings depending on a conditional. Something like this:

C# code:
public class SomeMappingProfile : Profile
{
    public SomeMappingProfile()
    {
        if (someCondition)
        {
            CreateMap<SomeSourceType, SomeDestinationType>()
                .ForAllMembers(opt => opt.MapFrom(src => src.Option1));
        }
        else
        {
            CreateMap<SomeSourceType, SomeDestinationType>()
                .ForAllMembers(opt => opt.MapFrom(src => src.Option2));
        }
    }
}
The above doesn't work (and I didn't really expect it to) but it's a pseudo-demonstration of what I need. Any thoughts?

Edit: Oh by the way, I know about resolvers etc, but I was hoping to create a mapping that can be used as an EF projection.

putin is a cunt fucked around with this message at 03:03 on May 21, 2018

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

Ugh. Either I'm going down a XY problem path, or I'm clashing with Microsoft's 'my way or the highway' approach. Possibly both.

So I have an ASP.NET Core WebAPI application. It can be launched in two different configurations (sort of a master/slave setup), and based on this launch option I want it to change some behaviour (eg. use different auth options, expose some folders rather than others), and the part that's giving me trouble: I want it to expose either one set of controllers or another. Some controllers are active in both, and the configurations / controller sets might change as the application grows, so I would rather not split the application into multiple assemblies if at all possible.

I thought I'd managed to get it working by adding a custom IStartup class, which configured the IApplicationBuilder and IServiceCollection in the appropriate way, then adding .AddControllersAsServices() and explicitly listing which controllers I wanted to be available. (This also came with the bonus of letting me explicitly call their constructors instead of having to trust the DI system.)

Well, it's mostly working, in the sense that if I try to call an endpoint on a controller that isn't listed I correctly get a 404. However, the absolute fuckers in the MVC internals appear to be still doing some reflection-based loading, because if I define the same endpoint route in two different controllers, it does not care in the slightest that only one of the controllers is currently registered in the application - it goes 'durr, this path exists somewhere else in the assembly' and throws a 500:

quote:

Request starting HTTP/1.1 POST http://localhost:8085/api/v1/logout 0
[15:52:47 DBG] Request successfully matched the route with name 'null' and template 'api/v1/logout'.
[15:52:47 ERR] Request matched multiple actions resulting in ambiguity. Matching actions:
MyButt.CurrentlyLoadedController.Logout (MyButt)
MyButt.VeryMuchNotLoadedController.Logout (MyButt)

Looking further into it, it seemed as if I could override this behaviour by also specifying a custom IApplicationFeatureProvider<ControllerFeature> (did I mention I loving love OO engineering?), but it didn't actually work. The next step looks like it might lie in the even more friendly-named IActionDescriptorCollectionProvider, but I guess this is where I should call it quits and just find a different solution, or put up with the limitation by adding more routes.

Anyway, even if this post gets immediately followed by a brutal takedown showing how my idea was fundamentally wrong in the first place, I still want to say this: death to reflection.

roadhead
Dec 25, 2001

.NET Core 2
.NET Framework 4.6.1
TFS Version 16.122.27409.2
Visual Studio is 2017 15.5.6

I have a Solution with three active projects in it.

A .NET Core Model, a WPF UI, and Unit Tests.

I wanted logging, so I look to see which Nuget package has the most downloads.

log4net, sounds great, love that apache license.

Builds fine on my machine, no problems.

Builds fine on the other developer's machines.

Doesn't build on TFS. Because it can't find the log4net reference. w t f.

Restore Nuget is in the tasks, but its only restoring it in the .NET Core Model project, not the UI WPF project where I actually want it?

nuget.Config is in play but has all the same sources that my local machine has, since I'm the one who checked it into git.

Just looking for some hints on places to look...

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

roadhead posted:

Just looking for some hints on places to look...

Start here:

https://fsprojects.github.io/Paket/getting-started.html

In my experience, whenever you're doing anything non-trivial with nuget dependencies (such as mixing runtimes), first install paket, then try to solve your problem. At the very least, you'll have plain text files to maintain and plain text outputs to read, instead of cryptic XML diffs and VS squiggles.

downout
Jul 6, 2009

NihilCredo posted:

Ugh. Either I'm going down a XY problem path, or I'm clashing with Microsoft's 'my way or the highway' approach. Possibly both.

So I have an ASP.NET Core WebAPI application. It can be launched in two different configurations (sort of a master/slave setup), and based on this launch option I want it to change some behaviour (eg. use different auth options, expose some folders rather than others), and the part that's giving me trouble: I want it to expose either one set of controllers or another. Some controllers are active in both, and the configurations / controller sets might change as the application grows, so I would rather not split the application into multiple assemblies if at all possible.

I thought I'd managed to get it working by adding a custom IStartup class, which configured the IApplicationBuilder and IServiceCollection in the appropriate way, then adding .AddControllersAsServices() and explicitly listing which controllers I wanted to be available. (This also came with the bonus of letting me explicitly call their constructors instead of having to trust the DI system.)

Well, it's mostly working, in the sense that if I try to call an endpoint on a controller that isn't listed I correctly get a 404. However, the absolute fuckers in the MVC internals appear to be still doing some reflection-based loading, because if I define the same endpoint route in two different controllers, it does not care in the slightest that only one of the controllers is currently registered in the application - it goes 'durr, this path exists somewhere else in the assembly' and throws a 500:


Looking further into it, it seemed as if I could override this behaviour by also specifying a custom IApplicationFeatureProvider<ControllerFeature> (did I mention I loving love OO engineering?), but it didn't actually work. The next step looks like it might lie in the even more friendly-named IActionDescriptorCollectionProvider, but I guess this is where I should call it quits and just find a different solution, or put up with the limitation by adding more routes.

Anyway, even if this post gets immediately followed by a brutal takedown showing how my idea was fundamentally wrong in the first place, I still want to say this: death to reflection.

This has to be happening somewhere that the application build the default routes with the controller and action names. That all has to be done thru reflection, right? Or am i misunderstanding when/how this err happens?

Essential
Aug 14, 2003
I learned something today that I wanted to share, just in case it helps anyone else. HttpClient should NOT be used in a using block, even though it implements IDisposable. This can cause some serious performance problems. For us, specifically we had an Azure Function that was scaling up in ways we couldn't understand. It turns out it was due to wrapping an httpclient in a using block. What can happen is it leaves ports open and can even utilize all ports and hang the system up while waiting to free up resources.

Many of you may already know this, but I wanted to share just in case. Here's the link I found originally on the issue: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ . Here is a link from Microsoft describing it: https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/

I was mistaken in that I thought anything that implements IDisposable should always be in a using block.

Potassium Problems
Sep 28, 2001
They've added HttpClientFactory in .NET Core 2.1 (currently in preview/RC), in part to help devs deal with stuff like that

https://blogs.msdn.microsoft.com/webdev/2018/02/28/asp-net-core-2-1-preview1-introducing-httpclient-factory/

Night Shade
Jan 13, 2013

Old School

override the nuget version in the build step to at least 4.5.0

NihilCredo posted:

Start here:

https://fsprojects.github.io/Paket/getting-started.html

In my experience, whenever you're doing anything non-trivial with nuget dependencies (such as mixing runtimes), first install paket, then try to solve your problem. At the very least, you'll have plain text files to maintain and plain text outputs to read, instead of cryptic XML diffs and VS squiggles.

or do this, paket is also good and iirc already has support for lock files
e: but it is another tool that doesn't come bundled with vs (maybe if you install f# into your visual studio), so there's that

Essential posted:

I was mistaken in that I thought anything that implements IDisposable should always be in a using block.

this is not helped by the fact that roslyn and resharper both will bitch at you about not either using{} it or implementing idisposable yourself

edit: also consider serilog, because structured logging is amazing

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

NihilCredo posted:

Ugh. Either I'm going down a XY problem path, or I'm clashing with Microsoft's 'my way or the highway' approach. Possibly both.

So I have an ASP.NET Core WebAPI application. It can be launched in two different configurations (sort of a master/slave setup), and based on this launch option I want it to change some behaviour (eg. use different auth options, expose some folders rather than others), and the part that's giving me trouble: I want it to expose either one set of controllers or another. Some controllers are active in both, and the configurations / controller sets might change as the application grows, so I would rather not split the application into multiple assemblies if at all possible.

I thought I'd managed to get it working by adding a custom IStartup class, which configured the IApplicationBuilder and IServiceCollection in the appropriate way, then adding .AddControllersAsServices() and explicitly listing which controllers I wanted to be available. (This also came with the bonus of letting me explicitly call their constructors instead of having to trust the DI system.)

Well, it's mostly working, in the sense that if I try to call an endpoint on a controller that isn't listed I correctly get a 404. However, the absolute fuckers in the MVC internals appear to be still doing some reflection-based loading, because if I define the same endpoint route in two different controllers, it does not care in the slightest that only one of the controllers is currently registered in the application - it goes 'durr, this path exists somewhere else in the assembly' and throws a 500:


Looking further into it, it seemed as if I could override this behaviour by also specifying a custom IApplicationFeatureProvider<ControllerFeature> (did I mention I loving love OO engineering?), but it didn't actually work. The next step looks like it might lie in the even more friendly-named IActionDescriptorCollectionProvider, but I guess this is where I should call it quits and just find a different solution, or put up with the limitation by adding more routes.

Anyway, even if this post gets immediately followed by a brutal takedown showing how my idea was fundamentally wrong in the first place, I still want to say this: death to reflection.

There's a whole lot to unpack here.

To start, you're trying to treat one project as though it were two. Fundamentally this is problematic, so I'd recommend splitting the projects. You can put all the business logic into a shared project so that you don't have to write everything twice.

There's no such thing as ASP.NET Core WebAPI - do you mean ASP.NET WebAPI or ASP.NET Core? I'm assuming from the content of the post it's the latter, which isn't a big deal but it will help you filter out useless stuff when Googling.

I'm also a bit confused by the message you're getting. How is it possible that controllers with two different names have the same route, have you manually configured the routing this way somewhere? Can you show us your Startup.cs?

Finally, I'm not sure what you mean about "trusting" the DI system. You configure it yourself, what's the issue you're having with the built-in DI stuff?

SimonChris
Apr 24, 2008

The Baron's daughter is missing, and you are the man to find her. No problem. With your inexhaustible arsenal of hard-boiled similes, there is nothing you can't handle.
Grimey Drawer

Essential posted:

I was mistaken in that I thought anything that implements IDisposable should always be in a using block.

Why does it implement IDisposable in the first place, if you are not supposed to dispose it?

EssOEss
Oct 23, 2006
128-bit approved
Because Microsoft is far from immune to bad software design (see DLL Hell v2.0: .NET Core Edition: .NET Standard Strikes Back: the Return of the MethodNotFoundException)

Essential
Aug 14, 2003

SimonChris posted:

Why does it implement IDisposable in the first place, if you are not supposed to dispose it?

What EssOEss said, but also because you should technically dispose it when it's no longer needed, which of course is a bit hard to define depending on how you are using it.

SimonChris
Apr 24, 2008

The Baron's daughter is missing, and you are the man to find her. No problem. With your inexhaustible arsenal of hard-boiled similes, there is nothing you can't handle.
Grimey Drawer

Essential posted:

Many of you may already know this, but I wanted to share just in case. Here's the link I found originally on the issue: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ .

Someone in the comments to that article claim that you then need to dispose the HttpResponseMessages, or you will have memory leaks. Like this:
code:
using (var response = await _httpClient.GetAsync(requestUri))
{
    response.EnsureSuccessStatusCode();
    var result = await response.Content.ReadAsStringAsync();
    return JsonConvert.DeserializeObject<t>(result);
}
This is not how it's shown in the linked Microsoft docs, but apparently they've been wrong before...

Mr Shiny Pants
Nov 12, 2012

Essential posted:

I learned something today that I wanted to share, just in case it helps anyone else. HttpClient should NOT be used in a using block, even though it implements IDisposable. This can cause some serious performance problems. For us, specifically we had an Azure Function that was scaling up in ways we couldn't understand. It turns out it was due to wrapping an httpclient in a using block. What can happen is it leaves ports open and can even utilize all ports and hang the system up while waiting to free up resources.

Many of you may already know this, but I wanted to share just in case. Here's the link I found originally on the issue: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ . Here is a link from Microsoft describing it: https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/

I was mistaken in that I thought anything that implements IDisposable should always be in a using block.

There was another poster here that had a problem when using the client in async methods. When an exception occurs in a HttpClient it will silently drop all other requests on different threads because it is one object IIRC.

If you just use HttpWebRequest do you still have this problem? I usually just use the HttpWebRequest directly, or does this also use the HttpClient?

EssOEss
Oct 23, 2006
128-bit approved
HttpWebRequest has been in .NET since the early days, whereas HttpClient is newer, so I would expect the former to be the lower level primitive - possibly HttpClient might be using HttpWebRequest internally (or at least some of the HttpClient implementations - there are several over the different .NET variations!).

Adbot
ADBOT LOVES YOU

nielsm
Jun 1, 2009



Speaking of HTTP clients, as far as I can tell HttpWebRequest is the only way to use NTLM authentication with the current credentials? Is that right?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply