Amir133
Amir133

Reputation: 2712

Redirect to URL with POST method in Asp.Net Core3.1

I am usig Asp.net core 3.1 and I must to redirect user to a url with Post Action, what should I do? is it possible?

public async Task<IActionResult> RedirectTo()
{
    // do something to generate a url 
    // redirectUrl = "https://xx.com/?token=zzzzz"
    
    redirect and Post to redirectUrl //how ???????????????????  
}

Upvotes: 1

Views: 1594

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

Check here for more information as to why this is not supported

You can't really do it BUT, there is a clever workaround here

            HttpResponse response = HttpContext.Current.Response;
            response.Clear();

            StringBuilder s = new StringBuilder();
            s.Append("<html>");
            s.AppendFormat("<body onload='document.forms[\"form\"].submit()'>");
            s.AppendFormat("<form name='form' action='{0}' method='post'>", url);
            foreach (string key in data)
            {
                s.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", key, data[key]);
            }
            s.Append("</form></body></html>");
            response.Write(s.ToString());
            response.End();

What this does, is create on html response with a form that will post a request to the required page with javascript.

You need to be in the same domain for this to work. If you redirect, then you can only do so with GET - parameters.

Upvotes: 4

Related Questions