5

I have an MVC WebAPI 2 project with a Controllers controller. The Method I'm trying to call is POST (Create). I need to access the referring URL that called that method yet, no matter what object I access, the referring URL either doesn't exist in the object or is null.

For example, I've added the HTTPContext reference and the following returns null:

var thingythingthing = HttpContext.Current.Request.UrlReferrer;

The Request object does not have a UrlReferrer property.

This returns null as well:

HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]

I cannot modify the headers because I need to be able to generate a link to the method and filter access by origin of the call.

Any particular place I should be look or, alternatively, any particular reason why those are returning null?

Edit: I have a solution for GET methods (HttpContext.Current.Request.RequestContext.HttpContext.Request.UrlReferrer) but not for POST methods.

user4593252
  • 3,496
  • 6
  • 29
  • 55

1 Answers1

6

See this answer. Basically, WebAPI requests use a different kind of request object. You can create an extension method that provides a UrlReferrer for you, though. From the linked answer:

First, you can extend HttpRequestMessage to provide a UrlReferrer() method:

public static string UrlReferrer(this HttpRequestMessage request)
{
    return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}

Then your clients need to set the Referrer Header to their API Request:

// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);

And now the Web API Request includes the referrer data which you can access like this from your Web API:

Request.UrlReferrer();
Community
  • 1
  • 1
Jesse Smith
  • 963
  • 1
  • 8
  • 21
  • The headers cannot be modified by the client in this case so I cannot use this for my purposes. I have a workaround that I could use but it would involve an intermediate page to redirect the call. I'm not keen on that. Also, see my question edit; – user4593252 Jul 19 '16 at 16:09
  • Ah. Carry on, then! – Jesse Smith Jul 19 '16 at 16:43