Redirect from asp.net web api post action
122,024
Solution 1
Sure:
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}
Solution 2
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
Solution 3
[HttpGet]
public RedirectResult Get()
{
return RedirectPermanent("https://www.google.com");
}
Solution 4
You can check this
[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{
string url = "https://localhost:44305/Templates/ReportPage.html";
System.Uri uri = new System.Uri(url);
return Redirect(uri);
}
Author by
Shahdat
Updated on September 18, 2020Comments
-
Shahdat over 3 years
I'm very new to ASP.NET 4.0 Web API. Can we redirect to another URL at the end of the POST action?, something like ...
Response.Redirect(url)
Actually I upload file from a MVC application (say
www.abcmvc.com
) through Web API (saywww.abcwebapi.com/upload
)Here
upload
is the POST action. I post a multi-part form to Web API upload controller's post action. After uploading I would like to redirect back towww.abcmvc.com
.Is this possible?
-
AaronLS about 10 yearsUsing this Redirect technique solved the "object moved to" WebAPI page I was getting with other redirect techniques. Also for Redirect temporary instead of permanent you can use
HttpStatusCode.Redirect
(302) or.RedirectMethod
(303) -
Brett over 8 years@Darin Dimitrov, this works. Why is it that when I use HttpStatusCode.Redirect instead, my client receives a 401 response?
-
Kaspar Lee almost 8 years@dotnetguy Please stop suggesting the same edit. If you want, post the code you changed in a separate answer. There is no point in continuing to edit, the reviewers will turn each edit down.