25

Is there a way how can I can get request origin value in the api controller when I'm calling some api endpoint with ajax call?

For example I'm making this call from www.xyz.com:

$http({
    url: 'http://myazurewebsite.azurewebsites.net/api/ValueCall/CheckForExistingValuers',
    method: "GET",
    params: { loanID: $scope.loanIdPopup }
}).success(function (data) {

}).error(function (data) {

});

Once on the api side, how can I get the www.xyz.com value?

CORS is working properly.

halfer
  • 19,824
  • 17
  • 99
  • 186
Laziale
  • 7,965
  • 46
  • 146
  • 262
  • possible duplicate of http://stackoverflow.com/questions/4258217/getting-the-http-referrer-in-asp-net – Theo Dec 28 '16 at 16:10
  • @Theo not a duplicate. – Laziale Dec 28 '16 at 16:11
  • How not? You are looking for the referrer URL, no? – Theo Dec 28 '16 at 16:12
  • If you got CORS working, you should be able to fetch the Origin-header. Most modern browsers sent it. – smoksnes Dec 28 '16 at 16:16
  • I've added example how to take origin value form request, but I'm curious why do you need it if you have EnableCors attribute or web.config section or custom cors policies for configuration origin values – ivamax9 Dec 28 '16 at 16:23

3 Answers3

36

What you're looking for is probably the origin-header. All modern browsers send it along if you're doing a cross domain request.

In an ApiController you fetch it like so:

if (Request.Headers.Contains("Origin"))
{
    var values = Request.Headers.GetValues("Origin");
    // Do stuff with the values... probably .FirstOrDefault()
}
smoksnes
  • 10,509
  • 4
  • 49
  • 74
  • 1
    I get this error: `"ExceptionMessage": "The given header was not found.", "ExceptionType": "System.InvalidOperationException",` I am using Postman. – Si8 Jan 31 '17 at 14:18
  • Then the consumer probably does not send that header. But all modern browsers send it if it's cross domain. – smoksnes Jan 31 '17 at 14:19
  • Ahhhhh... The Url I am using is "http://localhost" just debugging in VS and running postman, maybe that's why? – Si8 Jan 31 '17 at 14:21
  • That could be it. The browser adds the header when sending a request with ajax from one domain to another. – smoksnes Jan 31 '17 at 14:22
  • 1
    You are right, it worked from another solution but not in Postman. Awesome. Thank you! I already +1 your answer before your last answer ;) – Si8 Jan 31 '17 at 14:23
12

You can grab it from the API methods via current HTTP request headers collection:

  IEnumerable<string> originValues;
  Request.Headers.TryGetValue("Origin", out originValues)
jmoreno
  • 12,752
  • 4
  • 60
  • 91
ivamax9
  • 2,601
  • 24
  • 33
8
var originValue = Request.Headers["Origin"].FirstOrDefault();

// or

StringValues originValues;
Request.Headers.TryGetValue("Origin", out originValues);
A. Morel
  • 9,210
  • 4
  • 56
  • 45