I am trying to write some unit tests for this method, but I cannot figure out how to configure Request . In particular, I need to set the Query and the Referer header attribute.
public IActionResult Index() { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Home"); } var query = Request.Query; StringValues returnUrlValue; if (query.TryGetValue("returnUrl", out returnUrlValue)) { var returnUrl = returnUrlValue.ToString(); var referer = Request.Headers["Referer"].ToString(); if (string.IsNullOrEmpty(returnUrl) && !string.IsNullOrEmpty(referer)) { returnUrl = WebUtility.UrlEncode(referer); } if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl)) { ViewBag.ReturnUrl = returnUrl; } } return View(); }
I understand that a Request goes through the middleware before it ever gets to the controller, so it cannot be passed to the controller as a parameter. But the Request object on the controller is readonly and cannot be assigned. So something like the following will not work.
var controller = new LoginController(); controller.Request = new DefaultHttpRequest(new DefaultHttpContext()) { QueryString = new QueryString("?returnUrl") };
source share