Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add a Request Header in an Integration Test For an API Controller

I am creating an integration test for an API controller that requires custom header information in the request.

CONTROLLER

public IActionResult Delete([FromQuery] string param1, [FromQuery] string param2)
{
    …
    var id = Request.Headers["X-Id1"].ToString();
    var id2 = Request.Headers["X-Id2"].ToString();
    … 
}

How can I add this request headers in my integration test? I got stuck at the code below because _controller.ControllerContext is of type ControllerContext and I cannot convert an HttpControllerContext object to it. The error message is Cannot implicitly convert type 'System.Web.Http.Controllers.HttpControllerContext' to 'Microsoft.AspNetCore.Mvc.ControllerContext'

INTEGRATION TEST

[TestMethod]
public void Test()
{
    var request = new HttpRequestMessage();
    request.Headers.Add("X-Id1", "1");
    request.Headers.Add("X-Id2", "2");

    var controllerContext = new HttpControllerContext();
    controllerContext.Request = request;

    _controller.ControllerContext = controllerContext; // Error message shows here.
    _controller.Delete("a", "b");

    // Assertion here.
}

Is there another way to do this?

like image 773
Josh Monreal Avatar asked Oct 20 '25 04:10

Josh Monreal


1 Answers

Try this code

_controller.ControllerContext.HttpContext = new DefaultHttpContext();
_controller.ControllerContext.HttpContext.Request.Headers["X-Id1"] = "1";
_controller.ControllerContext.HttpContext.Request.Headers["X-Id2"] = "2";
like image 170
Roman Marusyk Avatar answered Oct 22 '25 18:10

Roman Marusyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!