Reputation: 192
So I have a website lets say its website1.com. From this website I call out to an api lets say its webapi.com/api/
Once I am in my get/post/ I want to get the url. However I do not want the webapi.com/api url I want the website1.com url.
Is it possible to find the url of a website that calls the api? Because currently any research only brings up
Url.Request.RequestUri.AbsoluteUri
but this yields webapi.com/api which is not what I want.
Any help would be greatly appreciated.
Here is a quick code example I got working.
[Route("")]
public IHttpActionResult Get()
{
try
{
return this.Url.Request.RequestUri.AbsoluteUri;
}
catch (Exception e)
{
ErrorLogService.SaveErrorLog(e, this.User.Identity.Name);
return InternalServerError();
}
}
Note I am trying to find the url that is sending a request to the api inside the api. If this is not possible and I have to send the url as a parameter that's fine but I am curious if its possible.
Upvotes: 0
Views: 2201
Reputation: 192
The solution is what I have marked however for a more complete answer I will just post here. You will infact have to pass the Referrer along from website1 to webapi.com/api. However you do not have to pass it along as a parameter.
What you can do or at least what I did was to pass it along the same way as I was with an Authorization token. Which the link @Romias provided has as the solution as well. Anywhere you pass a Bearer: 'your token' you simply add another header called Referrer: request.url.
Here request.url is website1.com. Now in my code I have an interceptor so any http call that is made is intercepted and then I add the bearer token which looks something like this in angular 5. Your setup might be different.
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (temp && temp.access_token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${temp.access_token}`
}
});
}
return next.handle(request);
}
}
From there I just appended the Authorization line to look like this.
Authorization: `Bearer ${currentUser.access_token}`, Referrer:request.url
So you can see I added a new header called Referrer and set it to the url.
From there you travel to the api and like the linked answer you simply have to put this code in your api method
public IHttpActionResult Get()
{
try
{
var temp = Request.Headers.Referrer == null ? "unknown" : Request.Headers.Referrer.AbsoluteUri;
return temp;
}
catch (Exception e)
{
ErrorLogService.SaveErrorLog(e, this.User.Identity.Name);
return InternalServerError();
}
}
And now temp has the url website1.com. You can then use or send this string however you want.
Hope this helps.
Upvotes: 0
Reputation: 14133
What your looking for is the REFERRER.
In WebApi 2 you don't have it, but you can workaround it.
Check this answer: https://stackoverflow.com/a/38462860/7720
Upvotes: 2