Cannot Create an instance of the Abstract class on interface 'Httprequest'

Asked

Viewed 819 times

2

I’m getting the following error:

Cannot Create an instance of the Abstract class on interface 'Httprequest'

inserir a descrição da imagem aqui

In that part of my code:

class FakeContext
{
    public static HttpContext FakeHttpContext()
    {
        var httpRequest = new HttpRequest("", "http://stackoverflow/", "");
        var stringWriter = new StringWriter();
        var httpResponse = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponse);

        var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                new HttpStaticObjectsCollection(), 10, true,
                                                HttpCookieMode.AutoDetect,
                                                SessionStateMode.InProc, false);

        httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                    BindingFlags.NonPublic | BindingFlags.Instance,
                                    null, CallingConventions.Standard,
                                    new[] { typeof(HttpSessionStateContainer) },
                                    null)
                            .Invoke(new object[] { sessionContainer });

        return httpContext;
    }
}

what I’m doing wrong ?

1 answer

1


You are confusing System.Web.HttpRequest of .Net Framework with the Microsoft.AspNetCore.Http.HttpRequest of .Net Core.

The second is an abstract class and as the error informs, you cannot instantiate it. You can use Dependency Injection to use it with the IHttpContextAccessor.

But in your case, to make one request, take the example of Microsoft itself. I believe you followed some example of . Net Framework but in a project using . Net Core.

Below is a simplified example:

public class HomeController : Controller
{
    private readonly IHttpClientFactory _clientFactory;

    public HomeController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task<HttpResponseMessage> FakeHttpContext()
    {
        var request = new HttpRequestMessage(HttpMethod.Get, "http://stackoverflow/");
        var client = _clientFactory.CreateClient();
        var response = await client.SendAsync(request);

        //Restante do seu código...

        return response;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.