Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url Referrer is not available in WebApi 2 MVC project

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.

like image 271
MetalPhoenix Avatar asked Jul 19 '16 14:07

MetalPhoenix


1 Answers

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();
like image 192
Jesse Smith Avatar answered Oct 17 '22 02:10

Jesse Smith