Get request origin in C# api controller
Asked Answered
S

3

27

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.

Sartorius answered 28/12, 2016 at 16:5 Comment(5)
possible duplicate of #4258717Betweentimes
@Betweentimes not a duplicate.Sartorius
How not? You are looking for the referrer URL, no?Betweentimes
If you got CORS working, you should be able to fetch the Origin-header. Most modern browsers sent it.Scotopia
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 valuesAdiaphorism
S
37

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()
}
Scotopia answered 28/12, 2016 at 16:24 Comment(5)
I get this error: "ExceptionMessage": "The given header was not found.", "ExceptionType": "System.InvalidOperationException", I am using Postman.Concepcionconcept
Then the consumer probably does not send that header. But all modern browsers send it if it's cross domain.Scotopia
Ahhhhh... The Url I am using is "localhost" just debugging in VS and running postman, maybe that's why?Concepcionconcept
That could be it. The browser adds the header when sending a request with ajax from one domain to another.Scotopia
You are right, it worked from another solution but not in Postman. Awesome. Thank you! I already +1 your answer before your last answer ;)Concepcionconcept
A
13

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

  IEnumerable<string> originValues;
  Request.Headers.TryGetValue("Origin", out originValues)
Adiaphorism answered 28/12, 2016 at 16:15 Comment(1)
Proper way to do this in .Net CoreFelske
B
8
var originValue = Request.Headers["Origin"].FirstOrDefault();

// or

StringValues originValues;
Request.Headers.TryGetValue("Origin", out originValues);
Berkeleianism answered 8/6, 2021 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.