How to get the url prefixes asp.net MVC - c#

I have a ASP.NET MVC application which will work on a IIS7.
I don't know the final URL yet, and that's the problem.
I want to get the URL-Parts between the Top-level-domain and my controller.
For examople: http://www.mydomain.com/myApplication/MyController/ControllerMethodshould return /myApplication/MyController/
This should also be possible, if the application is called via the standard method, for example http://www.mydomain.com/myApplication.
The Problem is that with my method it works perfectly if the full controller- and methodname is in the url, but as soon as there is only the controller name and the route takes the default index-method or there is no controller/method and the route takes the default controller/method, it will fail because my code puts wrong output.
I thought about hardcoding the controller-name and make a if-then-else orgy, but this doesn't seem very professional...
Maybe anyone of you has got an Idea.
Here's my function:
String segments = Request.Url.Segments;
System.Text.StringBuilder builder = new System.Text.StringBuilder();
String lastSegment = "";
int i= 0;
do
{
builder.Append(segments[i]);
lastSegment = segments[i++];
} while(!lastSegment.Equals("Home") && !lastSegment.Equals("Home/") && i < segments.Length);
return builder.toString();

Use the Url class to build the Urls for you http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper(v=vs.118).aspx

Related

Trying to find how a specific 32 hex character webform is generated from Netgear Managed Switch local UI webpage

I am trying to simulate navigating Netgear Managed Switch (GC108PP) local UI webpage in C#. When sending HttpWebRequest using a Chrome browser, I've learned using Fiddler - there are 3 WebForms that are generated when hitting this URL:
http://192.168.50.101
ends up being:
http://192.168.50.101/cgi/get.cgi?cmd=home_login&dummy=1582137153063&bj4=3f104a21e12a9584d36372142f16e35b
WebForms:
cmd=home_login
dummy=1582137153063 (time since epoch, this one was easy to figure out)
bj4=3f104a21e12a9584d36372142f16e35b (trying to figure out how to generate this one)
There is no HTTP API to reference from Netgear. I have tried just generating a 32 char string with:
private static Random random = new Random();
public static string randomString(int length)
{
const string chars = "abcdef0123456789";
return new string(Enumerable.Repeat(chars, length).Select(s =>s[random.Next(s.Length)]).ToArray());
}
However, I get ERROR 400 Bad Request.If I use a bj4 key/ID that gets generated by my browser statically in my code it works, but I want to be generating this webform properly.
Any ideas on how this WebForm might be be generated?
Found it in the JS...
function gotoLogin()
{
document.cookie = \"testcookie\";
cookieEnabled = (document.cookie.indexOf(\"testcookie\") != -1) ? true : false;
if (cookieEnabled == false)
{
alert(\"Browser does not accept cookies. Please configure your browser to accept cookies in order to access the Web Interface.\");
}
var fileVer = (new Date().getTime());
var url = \"login.html?aj4=\"+fileVer;
url = url + '&bj4=' + md5(url.split('?')[1]); //here!!!
window.location.href=url;
}

Determine if a given url (from a string) is from my domain or not

I'm trying to check from c# code if a given url is from my domain or not, in order to add the "nofollow" and "target _Blank" attributes for external links.
When i talk about external links i refer to any link outside my domain.
By default it does not have that attributes. I tried a lot of stuff, basically this is the part i need to fix:
public void PrepareLink(HtmlTag tag)
{
string url = tag.attributes["href"];
if (PrepareLink != null)
{
if (it is from an external site???)
{
tag.attributes["rel"] = "nofollow";
tag.attributes["target"] = "_blank";
}
}
Edit:
things i've tried:
string dominioLink = new Uri(url).Host.ToLower();
if (!dominioLink.Contains(myDomainURL))
{
tag.attributes["rel"] = "nofollow";
tag.attributes["target"] = "_blank";
}
Which has the issue that dont take in mind subdomains
i.e. if a link created is http://www.mydomain.com.anotherfakedomain.com, it will return true and work well.
I've looked in every Uri property but didn't seem to contains the base domain.
I'm currently using .NET Core 2.0.
thankS! please if you need any other data just let me know.
You can use the Uri.Host property to obtain the domain from a URL string, then compare it to your own. I suggest using a case-insensitive match.
var url = tag.attributes["href"];
var uri = new Uri(url);
var match = uri.Host.Equals(myDomain, StringComparison.InvariantCultureIgnoreCase)

Uri.EscapeDataString or HttpUtility.UrlEncode does not work for my case

I have an API in a project which I coded as following:
[Route("api/SearchCustomer/{customer}")]
[HttpGet]
public List<Customer> SearchCustomer(string customer)
{
return customerRepo.GetSearchJoined(customer);
}
At first, I got an issue when I am calling this API from my front end, if customer contains dot or space(for example: https://www.somesite.com/walmart Inc.), I will get 404 error(cannot found this API). I find an easy way to solve this problem. Just add a "/" will solve this problem.(https://www.somesite.com/walmart Inc./ )
Now I need to call this API in another project at the back end. So I did something like this:
var urlParm = "https://www.somesite.com/api/SearchCustomer/" + name + "/";
response = client.GetAsync(urlParm).Result;
var dataObjects = response.IsSuccessStatusCode ? response.Content.ReadAsAsync<IList<Customer>>().Result : null;
return dataObjects;
Unfortunately, adding the "/" at back does not work. I am still getting 404 error. Then, I tried to use Uri.EscapeDataString or HttpUtility.UrlEncode to encode "name".(Does C# have an equivalent to JavaScript's encodeURIComponent()?)
name = Uri.EscapeDataString(name)
or name = HttpUtility.UrlEncode(name)
or name = HttpUtility.UrlPathEncode(name)
var urlParm = "https://www.somesite.com/api/SearchCustomer/" + name + "/";
or var urlParm = = "https://www.somesite.com/api/SearchCustomer/" + name
response = client.GetAsync(urlParm).Result;
var dataObjects = response.IsSuccessStatusCode ? response.Content.ReadAsAsync<IList<Customer>>().Result : null;
return dataObjects;
I have tried all the different matches of above code. All of them did not work. I am still getting the 404 error. Does anyone know what I am doing wrong here?
Sorry for the typo, I removed some sensitive information so I deleted the "api" by mistake. The route is not the problem. I have tested that the api call from the back end worksif name contains only letters or numbers but fails when name contains dot.
The problem is not relevant the customer parameter is encoded or not. You should specify the routing and apply the request correctly. Firstly fix the route;
[Route("api/SearchCustomer/{customer}")]
Then apply the request.
https://www.somesite.com/api/SearchCustomer/samplecustomer

ASP.net not catching QueryString

I have created a ASP.net application,where i change the language base on its query string.
I have two servers both are https ,but one is redirected by netscaler
https://testMyLiveCode.com
https://myNetscalerServer.com/testapply-aU4uC6Q9dU94nHzVZA6zdtaQE433Xa2a/?
For eg
https://testMyLiveCode.com/?ln=en
This is my asp.net code
string strNewLanguage = Request.QueryString["ln"].ToLower();
SessionHelper.Language = strNewLanguage ;
string strNewURL = Request.RawUrl.ToLower().Replace("ln=" + Request.QueryString["ln"], "");
Response.Redirect(strNewURL);
What i actually do is that change the language depending on querystring and change the querystring and redirects
THis works perfectly with my https Server
https://testMyLiveCode.com/?ln=en
But this doesnt work with my netscaler url
https://myNetscalerServer.com/testapply-aU4uC6Q9dU94nHzVZA6zdtaQE433Xa2a/?
This is my url
And after i added the querystring to it,it does not work
https://myNetscalerServer.com/testapply-aU4uC6Q9dU94nHzVZA6zdtaQE433Xa2a/??ln=en
Can anyone help why this is not working as the url already has a ? in it???
Thanks for any help
My suggestion is to change the string which contains '?', it you can't then below instruction and code might help you
I am writing below code based on language array, you need to modify this based on your requirement, Hopefully this will help.It's bad code you have to modify this to make this good
string[] obj = new string[5] {"hi","en","ar","or","xy" };
string urlString = Request.RawUrl.ToLower();
int location = 0;
for (int i = 0; i < obj.Length; i++)
{
if (urlString.Contains("=" + obj[i]))
{
location = i;
break;
}
}
string strNewURL = Request.RawUrl.ToLower().Replace("ln=" + obj[location], "");
Response.Redirect(strNewURL);

WCF Service fails to send mail through MailDefinition

// stuff......
return SendCreationMail(Membership.GetUser((Guid)request.UserEntityId), request, new Control());
}
private const string TemplateRoot = "~/app_shared/templates/mail/";
private const string ServerRoot = TemplateRoot + "server/";
public static bool SendCreationMail(MembershipUser user, IServerAccountRequest request, Control owner)
{
var definition = new MailDefinition { BodyFileName = string.Concat(ServerRoot, "creation.htm"), IsBodyHtml = true };
var subject = "New {0} account created!".FormatWith(request.ServerApplicationContract.Id);
var data = ExtendedData(DefaultData, subject, user);
data.Add("<%ServerApplication%>", request.ServerApplicationContract.Id);
data.Add("<%ServerApplicationName%>", request.ServerApplicationContract.ApplicationName);
data.Add("<%AccountUsername%>", request.AccountUsername);
data.Add("<%ServerInfo%>", "/server/{0}/info".FormatWith(request.ServerApplicationContract.Id.ToLower()));
return definition.CreateMailMessage(user.Email, data, owner).Send(subject, ApplicationConfiguration.MailSenderDisplayName);
}
I get:
Value cannot be null. Parameter name: basepath
at System.Web.Util.UrlPath.Combine(String appPath, String basepath,
String relative)
at
System.Web.UI.WebControls.MailDefinition.CreateMailMessage(String
recipients, IDictionary replacements, Control owner)
at
Damnation.Website.Main.Common.MailTemplating.Server.SendCreationMail(MembershipUser
user, IServerAccountRequest request, Control owner)
at Damnation.Website.Main.Common.MailTemplating.Server.SendCreationMail(IServerAccountRequest
request)
at Damnation.Website.Main.Business.Model.ServerAccountRequest.UpdateRequestsAfterServerProcessing(IEnumerable`1
results)
Thing is I don't have an actual Control to pass to it, I'd like to know how to setup a control that avoids this senseless exception. I'm using a relative path... so this makes no sense.
The application that has the service is under ASP.NET WebForms .NET 4. The consumer application is a console application also under .NET 4
I had the same problem, and I learned that this is happening because it cannot find the path of the control when trying to execute your definition.CreateMailMessage. You want to create a blank web user control. Maybe this is not the most elegant solution but it does the work.
This is what I did:
1) Add a Web User Control file in your project, for example Test.ascx.
2) In your .svc file add the following code:
Page page = new Page();
Test test = (Test)page.LoadControl("Test.ascx");
3) Update your definition.CreateMailMessage line to:
return definition.CreateMailMessage(user.Email, data, test).Send(subject, ApplicationConfiguration.MailSenderDisplayName);
You will no longer get the basepath null exception.
I had the same problem but it was because I was on a project .NET console application, when I passed the code to ASP.NET not I run well without creating Page and Test.
I had the same error but the problem for me was that I was using relative paths for my BodyFileName and EmbeddedObjects. Changing them to absolute paths fixed this error for me.

Categories