Thursday, April 16, 2015

When someone posts to an Web API Controller and you return a HttpResponseMessage, you may spec where the user gets routed back to!

I continue to be amazed at the freedom I have to reach back up to a web site that spoke into me from the API side in ASP.NET MVC Web API controllers. Not unlike this, the following lets you change what it at the browser, only this time we are redirecting to another URL instead of replacing the existing HTML with our own HTML:

Uri uri = new Uri(myMagicString);
HttpResponseMessage httpResponseMessage =
      Request.CreateResponse(HttpStatusCode.Moved);
httpResponseMessage.Headers.Location = uri;
return httpResponseMessage;

 
 

Clearly, in this example myMagicString would contain a URL. If you want to just use the URL that the browser was at when it spoke into the API to begin with you may do so like this:

string myMagicString =
      System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

 
 

If you use this trick to route back to where one was you should probably trim away the URL line variables first like so:

if (myMagicString.Contains("?")) myMagicString = myMagicString.Split('?')[0];

No comments:

Post a Comment