How to call an ASP.NET WebMethod using PowerShell? - asp.net

It seems like ASP.NET WebMethods are not "web servicey" enough to work with New-WebServiceProxy. Or maybe it is, and I haven't figured out how to initialize it?
So instead, I tried doing it manually, like so:
$wc = new-object System.Net.WebClient
$wc.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$url = "http://www.domenicdenicola.com/AboutMe/SleepLog/default.aspx/GetSpans"
$postData = "{`"starting`":`"\/Date(1254121200000)\/`",`"ending`":`"\/Date(1270018800000)\/`"}"
$result = $wc.UploadString($url, $postData)
But this gives me "The remote server returned an error: (500) Internal Server Error." So I must be doing something slightly wrong.
Any ideas on how to call my PageMethod from PowerShell, and not get an error?

Try the proxy approach again if indeed your are using a WebMethod. If so, the URL resource should have the extension .asmx but your's shows that you are using a standard ASP.NET page .aspx.
A proxy simplifies the use of a WebMethod quite a bit e.g.:
C:\PS>$URI = "http://www.webservicex.net/uszip.asmx?WSDL"
C:\PS> $zip = New-WebServiceProxy -uri $URI -na WebServiceProxy -class ZipClass
What sort of error are you getting when you try to use New-WebServiceProxy?

Domenic - I am not a big PowerShell user, but the salient issue here is:
"PageMethods" are ScriptMethods and do not expose a WSDL or any other discovery vector and as such you must POST with a content-type application/json with post data urlencoded e.g. starting=[.net datetime string urlencoded]&ending=..... JSON encoding the input is incorrect.
Try using (HttpWebRequest)WebRequest.Create...... instead of WebClient, from which you would have to derive a class to enable changing the content type.
For instance, you could use something like this script and simply add a content type argument (or just hardcode it), something like this?
....
$req = [System.Net.HttpWebRequest]::Create($url);
$req.ContentType = "application/json";
$res = $req.GetResponse();
....

Related

How can I pass email with a + as asp.net web Api parameter

How can I pass "name+first#domain.com" as a parameter to the asp.net web api method? plus sign automatically get replaced with space ("name first#domain.com")
ASP.net 4.5
Thanks
Use HttpUtility.UrlEncode("name+first#domain.com") before you call the method.
And HttpUtility.UrlDecode to decode the string if necessary.
Update
To call the web api method from javascript and escape the +, then you can use: encodeURIComponent("name+first#domain.com")
To decode use System.Uri.UnescapeDataString(escapedParameter);
Try like this.
Change in the URI for your method of your api.
[Route("RegisterUser?email={email}")]
Now change the url of the method accordingly.
new URL for calling the mehod will be http://api/name_Controler/RegisterUser?email=escape('name+first#domain.com')
Of course you are encoding the URL right? I had a similar situation and this issue is intermittent. Any other character can be dealt with using HttpUtility.UrlEncode("!&~^((");
But + (plus) doesn't fit there, and as I said it happens sometimes. So I decided to switch to GetQueryNameValuePairs
var queryParams = this.Request.GetQueryNameValuePairs().ToList();
var userId = queryParams.Single(q => q.Key.ToLower() == "userid").Value;
var password = queryParams.Single(q => q.Key.ToLower() == "password").Value;
You still have to encode though

asp Server.Transfer put parameter

i googled many samples, all show such code
Server.Transfer("/default.asp?p=news")
but i get error -An invalid character was specified in the Path parameter for the MapPath method.
can you help me?
Server.Transfer method actually doesn't support any kind of querystring specified in the path. You can try to store the query parameter in a session value instead.
Some discussions:
http://classicasp.aspfaq.com/general/why-won-t-querystring-values-work-with-server-execute/server-transfer.html
The following might be a work around to using server.transfer or response.redirect.
Response.Write "<script language=javascript>window.location.href = '/default.asp?p=news';</script>"
You would have to include your querystring on the page that does the server transfer.
Ie:
page.asp?p=news would include:
Server.Transfer("default.asp")
default.asp would include:
sParam = Request("p") '<-- Your querystring value from page.asp
This should work, or if your app isn't flexible to do this, you can use Session to pass the value. It says here which methods are allowed for passing variables using Server.Transfer: http://msdn.microsoft.com/en-us/library/ms525800%28v=vs.90%29.aspx

How do we pass parameters when doing HTTP Post?

I am working on an app where we have to pass specific web api parameters to a web app using HTTP POST.
eg:
apimethod name
parameter1 value
parameter2 value
So do I use a string or URLEncodedPostData to send that data?
It would be good if u help me with a code eg.
I am using something like this but it doesnt post the data to the server.
Though the response code is ok/200 and I also get get a parsed html response when i read the httpresponse input stream. But the code doesnt post anything. So unable to get the expected response.
_postData.append("method", "session.getToken");
_postData.append( "developerKey", "value");
_postData.append( "clientID", "value");
_httpConnection = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
String encodedData = _postData.toString();
_httpConnection.setRequestMethod(HttpConnection.POST);
_httpConnection.setRequestProperty("User-Agent", "BlackBerry/3.2.1");
_httpConnection.setRequestProperty("Content-Language", "en-US");
_httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
_httpConnection.setRequestProperty("Content-Length",(new Integer(encodedData.length())).toString());
os = _httpConnection.openOutputStream();
os.write(requeststring.getBytes());`
The code you posted above looks correct - although you'll want to do a few more things (maybe you did this already but didn't include it in your code):
Close the outputstream once you've written all the bytes to it
Call getResponseCode() on the connection so that it actually sends the request
POSTed parameters are usually sent in the response BODY, which means URL-encoding them is inappropriate. Quote from the HTTP/1.1 protocol:
Note: The "multipart/form-data" type has been specifically defined
for carrying form data suitable for processing via the POST
request method, as described in RFC 1867 [15].
The post method allows you to use pretty arbitrary message bodies — so it is whatever format the server wants.

ASP.NET: Get *real* raw URL

In ASP.NET, is there any way to get the real raw URL?
For example, if a user browse to "http://example.com/mypage.aspx/%2F", I would like to be able to get "http://example.com/mypage.aspx/%2F" rather than "http://example.com/mypage.aspx//".
I would of course like a clean way to do it, but I can live with a hacky approach using reflection or accessing obscure properties.
At the moment, I try to use the uri in the Authorization-header (which works), but I cannot rely on that always being there.
EDIT:
What I really want to do is to be able to distinguish between "http://example.com/mypage.aspx/%2F" and "http://example.com/mypage.aspx/%2F%2F".
It looks like ASP.NET first converts "%2F%2F" into "//" and then converts the slashes into a single slash.
So just re-encoding it is not going to work.
I wasn't able to test this because it only works in IIS and not the ASP.NET Development Server that is part of Visual Studio, but try:
Request.ServerVariables[ "HTTP_URL" ]
The following code works for me:
IServiceProvider serviceProvider = (IServiceProvider)HttpContext.Current;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)serviceProvider.GetService(typeof(HttpWorkerRequest));
string realUrl = workerRequest.GetServerVariable("HTTP_URL");
Note that this only works when running on the IIS and not under f.x. ASP.NET Development Server!
Thanks to Lucero for the answer in another thread and Zhaph for pointing me to the thread.
See also:
Get the exact url the user typed into the browser
Server.HtmlEncode(Request.RawUrl);
The raw URL is defined as the part of the URL following the domain information. In the URL string http://www.contoso.com/articles/recent.aspx, the raw URL is /articles/recent.aspx. The raw URL includes the query string, if present.
see also:link text
I can't test here, but this might be what you need:
Request.Url.AbsoluteUri
Request.RawUrl will return the application relative path(including querystring info) while Request.Url will return the complete path(including querystring info).
For more information, see "Making sense of ASP.NET paths".
Well, you could just encode it back to the url-encoded version.
Get the url from the request and urlencode only the query string part and then concatenate them

how can an .ASPX page get its file system path?

I have a page something.aspx, with associated codebehind something.aspx.cs. In that codebehind, I want to know the filesystem location of something.aspx. Is there any convenient way to get it?
Update: I got several excellent answers, which unfortunately didn't work because of something else crazy I'm doing. I'm encoding some additional information on the URL I pass in, so it looks like this:
http://server/path/something.aspx/info1/info2/info3.xml
The server deals with this OK (and I'm not using querystring parameters to work around some other code that I didn't write). But when I call Server.MapPath(Request.Url.ToString()) I get an error that the full URL with the 'info' segments isn't a valid virtual path.
// File path
string absoluteSystemPath = Server.MapPath("~/relative/path.aspx");
// Directory path
string dir = System.IO.Path.GetDirectoryName(absoluteSystemPath);
// Or simply
string dir2 = Server.MapPath("~/relative");
Request.PhysicalPath
Server.MapPath is among the most used way to do it.
string physicalPath = Server.MapPath(Request.Url);
Server.MapPath( Request.AppRelativeCurrentExecutionFilePath )

Resources