Question

How do you set the result of an action result to use Post and not Get. I need to redirect the result to an external site that requires the data to be sent using the post method.

(Would like to know also how to redirect to another action with a httpverbs.post filter - but not as important for me at this point).

Was it helpful?

Solution

By definition a redirect will generate a GET request. You could do the POST on their behalf using a WebClient, but you can't redirect their browser there using POST. If the post needs to go to another site, you might want to simply generate the form action so that it posts there directly.

OTHER TIPS

You could do the following: Return an action result that emits a form with the fields and uses some JavaScript to automatically post the emitted form.

Here is the code for HttpPostResult

public class HttpPostResult :
    ActionResult
{

    string _formName;
    NameValueCollection _inputs;
    string _url;

    public HttpPostResult(
        string url ,
        NameValueCollection inputs ,
        string formName = "form1" )
    {
        _url = url;
        _inputs = inputs;
        _formName = formName;
    }

    public override void ExecuteResult( ControllerContext context )
    {
        //  Html generation
        var html = new StringBuilder();
        html.Append( "<html><body onload=\"document.form1.submit()\">" );
        html.AppendFormat(
            "<form name=\"{0}\" method=\"POST\" action=\"{1}\">" ,
            _formName ,
            _url
            );
        foreach( var key in _inputs.AllKeys )
            html.AppendFormat(
                "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,
                key ,
                _inputs[ key ]
                );
        html.Append( "</form></body></html>" );

        //  Write to Response stream
        context.HttpContext.Response.Write( html.ToString() );
        context.HttpContext.Response.End();
    }

}

Then when you require an action result in your controllers to return a POST and not a GET use:

return new HttpPostResult( url , inputs );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top