'Can not instantiate proxy of class: System.Net.HttpWebRequest. Could not find a parameterless constructor

I am upgrading my C# function app from .net 3.1 to 6.0`.

When I run my test cases, I found that, 1 of my test case failed with the below error.

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: System.Net.HttpWebRequest. Could not find a parameterless constructor.

Basically, I am trying to mock HttpWebRequest and below is my piece of code for that.

var httpWebRequest = new Mock<HttpWebRequest>();

It is working fine in .Net 3.1. I am using Moq version 4.16.1 in both the projects.



Solution 1:[1]

Both HttpWebRequest constructors are obsolete and should not be used. You have to use the static function "Create" to create a new instance of the HttpWebRequest class:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");

To solve your issue, use the HttpClient class instead. This class has a parameterless constructor.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Coragi