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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With