I am developing a Classified Web Site. This web site has a lot of Sub Domains like dubai.sitedomain.com, london.sitedomain.com, newyork.sitedomain.com etc depending on cities. I am using Angularjs as my front end and Web Api as server side.
My requirement is I want to get the subdomain on my Web Api Action. Like:
[HttpGet]
[Route("GetAds")]
public IHttpActionResult GetAds()
{
// Here I want to know, from which subdomain the request has been sent
// so I can filter my ads according to the city
var city = "city from subdomain";
var list = _adService.GetAdsByCity(city);
return Ok(list);
}
Use Request.Headers.Referrer.Host.Replace(".sitedomain.com", string.Empty);
Of course this will only work on your live environment, so you may need to modify this to work differently on your local test domains, or provide some sort of default fallback. I would suggest extracting this to a method in a common library, as it's likely you will need it in many places.
Alternatively, if you know that it will always be the first part, you can use
Request.Headers.Referrer.Host.Substring(0, Request.Headers.Referrer.Host.IndexOf("."));
You can extract it from
var x = Request.Host.Value;
Which will give you "london.sitedomain.com:port"
You can then do a
x.Split('.')[0] //(for example)
To get the subdomain
This should get you what you need.
HttpContext.Current.Request.UserHostAddress;
HttpContext.Current.Request.UserAgent;
HttpContext.Current.Request.Url.OriginalString;
There is also:
Request.Url.Scheme
Request.Url.Authority
Request.ApplicationPath
You can get host from HttpRequestMessage.RequestUri.Host:
string host = Request.RequestUri.Host;
int index = host.IndexOf('.');
return host.Substring(0, index + 1)
Related
I am using Elizabeth's wrapper from https://github.com/mozts2005/ZendeskApi_v2
I want to pull a list of agents. I don't see any built in Function that will allow that.
I have tried using the endpoint of /api/v2/users.json?role=agent with the GetAllUsers() function but it still returns all of them.
Right now, I am going to add a custom field to be able to search for them, but that should not be the case, especially since Zendesk's API does have an option for returning users based on their role: /api/v2/users.json?role[]=admin&role[]=end-user
Can anyone help me out?
You can give a try to the Zendesk Search API:
from urllib.parse import urlencode
import requests
results = [] # Empty list to collect pagination results
credentials = 'your_zendesk_email', 'your_zendesk_password'
session = requests.Session()
session.auth = credentials
params = {
'query': 'type:user role:agent'
}
url = 'https://your_subdomain.zendesk.com/api/v2/search.json?' + urlencode(params)
while url:
response = session.get(url)
data = response.json()
results += data['results']
url = data['next_page'] # should return false according to the doc when the last page is reached
Useful resources:
zendesk api python tutorial
zendesk api pagination
Search endpoint seems to be supported also in the c# library you are using.
I want to get the current domain name in asp.net c#.
I am using this code.
string DomainName = HttpContext.Current.Request.Url.Host;
My URL is localhost:5858but it's returning only localhost.
Now, I am using my project in localhost. I want to get localhost:5858.
For another example, when I am using this domain
www.somedomainname.com
I want to get somedomainname.com
Please give me an idea how to get the current domain name.
Try getting the “left part” of the url, like this:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.
Do note that the resulting URL will not have a trailing slash.
Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.
Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.
Here is a screenshot of Request.RequestUri and all its properties for everyone's reference.
You can try the following code :
Request.Url.Host +
(Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..
Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.
Personally, I'd suggest special-casing www. for this.
string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;
if (host.StartsWith("www."))
return host.Substring(4);
else
return host;
Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.
string host = ...;
int lastDot = host.LastIndexOf('.');
int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');
if (secondToLastDot > -1)
return host.Substring(secondToLastDot + 1);
else
return host;
Getting the port is just like other people have said.
HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port
the Request.ServerVariables object works for me. I don't know of any reason not to use it.
ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for
You can try the following code to get fully qualified domain name:
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
Here is a quick easy way to just get the name of the url.
var urlHost = HttpContext.Current.Request.Url.Host;
var xUrlHost = urlHost.Split('.');
foreach(var thing in xUrlHost)
{
if(thing != "www" && thing != "com")
{
urlHost = thing;
}
}
To get base URL in MVC even with subdomain www.somedomain.com/subdomain:
var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";
string domainName = HttpContext.Request.Host.Value;
this line should solve it
Try this:
#Request.Url.GetLeftPart(UriPartial.Authority)
I'm trying to create a parsing system for c#, to block my program from fetching images from "banned" websites that are located in a list. I have tried using bool class, to do a Regex.Replace operation, unfortunately it didn't work out.
To elaborate on what I exactly would like, this is an example:
I have a List BannedSites = new List { "site" };
if(Bannedsites.Contains(input))
{
Don't go to that site
}
else
{
Go to that site
}
Though the error I mostly get is I have "site" in the list, though if someone does "site " with a space afterwards it goes to the else statement, since it doesn't directly exist in the list, or if someone does "site?" and we know a questionmark at the end of the url doesn't make a difference usually to access the site, so they bypass it again. Is it possible to do something that if the input contains "site", WITHING the string, for it to not go to the site. Sorry if this is a simple code, though I haven't been able to figure it out and google didn't help.
Thanks in advance!
You can use LINQ's .Any to help with that:
if(Bannedsites.Any(x => input.Contains(x)) {
// Don't go to that site
} else {
// Go to that site
}
Remember to use .ToUpperInvariant() on everything to make it case-insensitive.
If you make sure that you only have the domain names (and arguably ips) in the list Bannedsites then you can look for the domain only.
To get the domain of a Uri, do as follows:
var uri = new Uri("http://stackoverflow.com/questions/11060418/c-sharp-string-parsing-containing-in-a-list");
Console.WriteLine(uri.DnsSafeHost);
The output is:
stackoverflow.com
Now you can get it to work like this (remember to store in upper case in Bannedsites):
var uri = new Uri(input)
if(Bannedsites.Contains(uri.DnsSafeHost.ToUpper(CultureInfo.InvariantCulture)))
{
//Don't go to that site
}
else
{
//Go to that site
}
This will also ensure that the domain didn't appear as a part of another string by chance, for example as part of a parameter.
Also note that this method will give you subdomains, so:
var uri = new Uri("http://msdn.microsoft.com/en-US/");
Console.WriteLine(uri.DnsSafeHost);
returns:
msdn.microsoft.com
and not only:
microsoft.com
You may also verify that the uri is valid with uri.IsWellFormedOriginalString():
var uri = new Uri(input)
if(uri.IsWellFormedOriginalString() && Bannedsites.Contains(uri.DnsSafeHost))
{
//Don't go to that site
}
else
{
//Go to that site
}
Now, let's say that you want to take into account the detail of subdomains, well, you can do this:
var uri = new Uri(input)
if(uri.IsWellFormedOriginalString() && Bannedsites.Any(x => uri.DnsSafeHost.EndsWith(x))
{
// Don't go to that site
}
else
{
// Go to that site
}
Lastly if you are banning particular pages not whole webs (in which case caring for the subdomains makes no sense), then you can do as follows:
var uri = new Uri(input)
if(uri.IsWellFormedOriginalString() && Bannedsites.Contains((uri.DnsSafeHost + uri.AbsolutePath)))
{
//Don't go to that site
}
else
{
//Go to that site
}
Using AbsolutePath you take care of those "?" and "#" often used to pass parameters, and any other character that doesn't change the requested page.
You may also consider using Uri.Compare and store a list of Uri instead of a list of strings.
I leave you the task of making the comparisons case invariant as RFC 1035 says:
"
For all parts of the DNS that are part of the official protocol, all
comparisons between character strings (e.g., labels, domain names, etc.)
are done in a case-insensitive manner.
"
I need to display the location and city name when a user enters a ZIP Code. How do I get the corresponding location names?
I would use a website like
http://www.zipinfo.com/search/zipcode.htm
and just send the zipcode to that, retrieve the input, parse for the city name, easy as that.
Try the USPS zipcode API - http://www.usps.com/webtools/welcome.htm
You can use the PlaceFinder geocoding web service to make REST based requests using the postal code you want to resolve to a name. The service supports both XML and JSON response formats. Here is a listing of the response elements returned by the service.
Using .NET, you would leverage the client or request/response classes in the System.Net namespace to make a request to the service and process the reponse.
The simplest way would be to use strings. You could alternatively create a ZIP class, if you wanted to get fancy.
using System;
using System.Collections.Generic;
class Program
{
// declare your variable
private static Dictionary<string, string> zipLookup;
public static void CreateZips()
{
zipLookup = new Dictionary<string, string>();
zipLookup.Add("90210", "Beverly Hills");
// fill all other values, probably from a db
}
static void Main(string[] args)
{
CreateZips();
var test = "90210";
if (zipLookup.ContainsKey(test))
{
Console.WriteLine(test.ToString() + "=" + zipLookup[test]);
}
else
{
Console.WriteLine(test.ToString() + " location unknown");
}
}
}
For more details on ZIPs, check out Wikipedia
I work in the address verification industry for a company called SmartyStreets. The solutions presented here are all functional in a variety of ways, but beware of their limitations and specialties. For example, Yahoo's service is more like address suggestion, not validation. The USPS web service is quite limited in the results it returns, for example: you won't get the County and Component data of an address, actual deliverability, etc.
For a more flexible, free solution -- may I suggest our LiveAddress API? It's a REST-ful endpoint which, given a street address (for example) and ZIP code, will fully and accurately complete the entire address.
Alternatively, you can use https://thezipcodes.com/
This has almost all the data that I used for the search.
Use http://thezipcodes.com/docs to use the API.
I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.
ie.
in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media
out: www.website.com/default.aspx
What would be the best way to achieve this?
System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
This gives the output: http://www.website.com/default.aspx
[The Uri class does require the protocol, http://, to be specified]
GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).
Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.
Here is a simple trick
Dim uri = New Uri(Request.Url.AbsoluteUri)
dim reqURL = uri.GetLeftPart(UriPartial.Path)
Here is a quick way of getting the root path sans the full path and query.
string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");
This may look a little better.
string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);
if (rawUrl.Contains("/post/"))
{
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
if (hasQueryStrings)
{
Uri uri = new Uri(rawUrl);
rawUrl = uri.GetLeftPart(UriPartial.Path);
HtmlLink canonical = new HtmlLink();
canonical.Href = rawUrl;
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);
}
}
Followed by a function to properly fetch the application URL.
Works perfectly.
I'm guessing that you want to do this because you want your users to see pretty looking URLs. The only way to get the client to "change" the URL in its address bar is to send it to a new location - i.e. you need to redirect them.
Are the query string parameters going to affect the output of your page? If so, you'll have to look at how to maintain state between requests (session variables, cookies, etc.) because your query string parameters will be lost as soon as you redirect to a page without them.
There are a few ways you can do this globally (in order of preference):
If you have direct control over your server environment then a configurable server module like ISAPI_ReWrite or IIS 7.0 URL Rewrite Module is a great approach.
A custom IHttpModule is a nice, reusable roll-your-own approach.
You can also do this in the global.asax as you suggest
You should only use the 301 response code if the resource has indeed moved permanently. Again, this depends on whether your application needs to use the query string parameters. If you use a permanent redirect a browser (that respects the 301 response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-media and load .../default.aspx - you'll never even know about the query string parameters.
Finally, you can use POST method requests. This gives you clean URLs and lets you pass parameters in, but will only work with <form> elements or requests you create using JavaScript.
Take a look at the UriBuilder class. You can create one with a url string, and the object will then parse this url and let you access just the elements you desire.
After completing whatever processing you need to do on the query string, just split the url on the question mark:
Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)
Granted, my solution is in VB.NET, but I'd imagine that it could be ported over pretty easily. And since we are only looking for the first element of the split, it even "fails" gracefully when there is no querystring.