Sam
Sam

Reputation: 5657

How can I do a RedirectToAction but as a POST instead of a GET?

We have a login method in a Authentication Controller that looks like this:

[HttpPost, ValidateModelState]
public ActionResult Login()
{
    var certificateName = GetCertificate();

GetCertificate() looks like this:

public string GetCertificate()
{
    var headerCertificateValue = Request.Headers.Get("X-ARR-ClientCert");
    return headerCertificateValue;

Basically we are using a cert in a header for authentication. So right now we are in the middle of trying to test that the cert header will work.

I have a form that looks like this to Mock our cert serving mechanism:

    using (Html.BeginForm("MockEcaCertLogin", "Authentication", new { area = "Login" }, FormMethod.Post))
    {
        @Html.ValidationSummary(true)
        @Html.AntiForgeryToken()
        <h1 class="bg-info">Mock ECA Login</h1>
        <div class="margin-bottom-20 margin-top-20">

            @Html.DropDownList("CertName", new List<SelectListItem>()
            {
                new SelectListItem() { Text = "First Last", Value = "First.Last.M.CCCdddddddddd.ID" },
                new SelectListItem() { Text = "First Last", Value = "FirstLast" },
            })

            <button type="submit" class="btn btn-default">Login</button>

        </div>
    }

This posts here:

[HttpPost, ValidateAntiForgeryToken]
public RedirectToRouteResult MockEcaCertLogin(string certName)
{
    Request.Headers.Add("X-ARR-ClientCert", certName);
    return RedirectToAction("Login");
}

which should go back to the original Login method and the cert would be in the header ready for the authentication so we can test that it works.

The problem is that a RedirectToRouteResult cannot be a post. How can I achieve this? Does anyone know?

Upvotes: 0

Views: 1783

Answers (1)

Sam
Sam

Reputation: 5657

This worked for me:

        [HttpPost, ValidateAntiForgeryToken, ValidateModelState]
        public void MockEcaCertLogin(string certName)
        {
            var urlHelper = new UrlHelper(this.HttpContext.Request.RequestContext);
            var destinationUrl = urlHelper.Action("Login", "Authentication");

            var headers = new NameValueCollection();
            headers.Add("X-ARR-ClientCert", certName);
            HttpContext.Server.TransferRequest(destinationUrl, true, "POST", headers);
        }

Upvotes: 1

Related Questions