ASP.NET's equivalent of PHP's $_GET and $_POST? - asp.net

As thet title says.
I'm new to asp.net, and I'm sorta trying to build some AJAX-stuff to learn.

ASP.Net AJAX may also be worth reading as there are some built-in things that could be useful.
"Request.QueryString" and "Request.Form" are the likely answers to the title question.

Following up with marr75's response, the Request property exposes a dictionary of GETed and POSTed variables.

See http://msdn.microsoft.com/en-us/library/swe97x0b.aspx.
It explains how to access the response and request context. If you're going to do ajax stuff, you might want to think about WCF REST, in which case, it's totally different and I would recommend going through some tutorials to see how the http elements of the application are abstracted away. In any event, in a lot of ASP.NET development, you don't touch the response and request contexts directly.

Request object is a map of all the request headers - both from the POST request and URL encoded params:
//This will retrieve the value of "SomeHeader" from the request
//e.g. http://localhost/page.aspx?SomeHeader=thisisvalue
string value = HttpContext.Current.Request["SomeHeader"];
//value == "thisisvalue"

Related

Is it possible to use nested resource in case of POST?

I use Play Framework 2.2.X.
Is it possible to map this route?:
POST /api/constructors/:constructorId/cars CarCrudController.create(constructorId)
I get a BadRequest (code 400) when hitting this route.
IMO, it seems that Play allows nested resources only for reads: GET instead of POST.
Is it possible?
Nested routes are supported in any HTTP method. You can checkout the samples from the github for some examples. The computer-database example, has the following routes.conf:
# Delete a computer
POST /computers/:id/delete controllers.Application.delete(id:Long)
The bad request response could be related with the content-type of your request or the post content itself, and nothing to do with the nested routes.

Is it considered bad practice to perform HTTP POST without entity body?

I need to invoke a process which doesn't require any input from the user, just a trigger. I plan to use POST /uri without a body to trigger the process. I want to know if this is considered bad from both HTTP and REST perspectives?
I asked this question on the IETF HTTP working group a few months ago. The short answer is: NO, it's not a bad practice (but I suggest reading the thread for more details).
Using a POST instead of a GET is perfectly reasonable, since it also instructs the server (and gateways along the way) not to return a cached response.
POST is completely OK. In difference of GET with POST you are changing the state of the system (most likely your trigger is "doing" something and changing data).
I used POST already without payload and it "feels" OK. One thing you should do when using POST without payload: Pass header Content-Length: 0. I remember problems with some proxies when I api-client didn't pass it.
If you use POST /uri without a body it is something like using a function which does not take an argument .e.g int post (void); so it is reasonable to have function to your resource class which can change the state of an object without having an argument. If you consider to implement the Unix touch function for a URI, is not it be good choice?
Yes, it's OK to send a POST request without a body and instead use query string parameters. But be careful if your parameters contain characters that are not HTTP valid you will have to encode them.
For example if you need to POST 'hello world' to and end point you would have to make it look like this: http://api.com?param=hello%20world
Support for the answers that POST is OK in this case is that in Python's case, the OpenAPI framework "FastAPI" generates a Swagger GUI (see image) that doesn't contain a Body section when a method (see example below) doesn't have a parameter to accept a body.
the method "post_disable_db" just accepts a path parameter "db_name" and doesn't have a 2nd parameter which would imply a mandatory body.
#router.post('/{db_name}/disable',
status_code=HTTP_200_OK,
response_model=ResponseSuccess,
summary='',
description=''
)
async def post_disable_db(db_name: str):
try:
response: ResponseSuccess = Handlers.databases_handler.post_change_db_enabled_state(db_name, False)
except HTTPException as e:
raise (e)
except Exception as e:
logger.exception(f'Changing state of DB to enabled=False failed due to: {e.__repr__()}')
raise HTTPException(HTTP_500_INTERNAL_SERVER_ERROR, detail=e.__repr__())
return response

ajax request that returns json array, IE6/7 is caching it and data is not fresh

for some reason, IE6/7 is caching the ajax call that returns a json result set back.
My page makes the call, and returns a json result which I then inject into the page.
How can I force IE6/7 to make this call and not use a cached return value?
You might want to add
Cache-Control: no-cache
to your HTML response headers when you're serving the JSON to tell the browser to not to cache the response.
In ASP.NET (or ASP.NET MVC) you can do it like this:
Response.Headers.Add("Cache-Control", "no-cache");
you can change your settings in ie, but the problem most likely lies on your server. You can't go out and change all your users' browser settings. But if you want to at least check it on your browser, go to Internet Options->General (Tab)->Browsing History(section)->Settings (button)->"Every time I visit the webpage"
Make sure you set it back, though, at some point.
To fix it on the server, have a look at http://www.mnot.net/cache_docs/
Using curl (w/ cygwin) for debugging is your great way to figure out what's actually being sent across the wire.
If cache-control doesn't work for you (see DrJokepu's answer), according to the spec the content from any URL with a query string should be non-cacheable, so you might append a pointless query parameter to your request URL. The value doesn't matter, but if you really want to be thorough you can append the epoch value, e.g.:
var url = "myrealurl?x=" + (new Date()).getTime();
But this is a hack; really this should be solved with proper caching headers at the server end.
In the controller action that returns a JsonResult, you need to specify in your headers to avoid caching:
ControllerContext.HttpContext.Response.AddHeader("Cache-Control", "no-cache");

how to get the content of a value posted as the body in asp classic?

I've seen a couple of rest examples where the xml message gets posted in the body of the http request, and not in a named parameter...
in classic asp I have the request.form object that allows me to get the posted values, but I have to specify the name of the parameter...
is there some way to get the whole content of the post?
I would need the equivalent of
request.serverVariables("QUERY_STRING"), but for the post, not the get part of the http request...
( http://www.w3schools.com/ASP/coll_servervariables.asp )
would I have to use request.binaryRead()???
thanks a lot
ps: in java, I cold achieve this using request.getReader()...
how to get a the value of an http post as a whole? parsing restful post
--
just to clarify thing a little bit
when I say post a value as the body, I mean that the content of the message is not enconded like param1=value1&param2=value2...paramx=valuex
the message is the body itself... you can achieve this with any ajax library (like prototype) to test ir I'm using a firefox plugin that let you do that, it's named POSTER
https://addons.mozilla.org/en-US/firefox/addon/2691
A developer tool for interacting with web services and other web resources that lets you make HTTP requests, set the entity body, and content type. This allows you to interact with web services and inspect the results...
You didn't specify either what actual content type is being posted nor what you intented to do with it once you've acquired it.
Lets assume for a moment that the content is XML and you want to load it into an XML DOM.
A useful fact about the Request object is that it implements IStream where the stream is the entity body of the POST. Another useful fact is MSXML DOMDocument load method can accept an implementation of IStream. Hence:-
Dim xml: Set xml = CreateObject("MSXML2.DOCDocument.3.0")
xml.async = false
xml.load Request
This code loads the posted entity body into the DOM.
I think I found it
if you issue str( request.form ) you get the raw value of the form element...
works also with request.querystring and request.cookies
it doesn't work with request.serverVariables, throws an exception...
oh, and inspecting the debugger I've also found a completely undocumented property, request.body, that seems to behave just like the request.form property...
Are you trying to loop through all the posted values from the form? If so in ASP.OLD you could do this:
For Each Field in Request.Form

Process raw HTTP request content

I am doing an e-commerce solution in ASP.NET which uses PayPal's Website Payments Standard service. Together with that I use a service they offer (Payment Data Transfer) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form :
SUCCESS
first_name=Jane+Doe
last_name=Smith
payment_status=Completed
payer_email=janedoesmith%40hotmail.com
payment_gross=3.99
mc_currency=USD
custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham
Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.
Something like this placed in your onload event.
if (Request.RequestType == "POST")
{
using (StreamReader sr = new StreamReader(Request.InputStream))
{
if (sr.ReadLine() == "SUCCESS")
{
/* Do your parsing here */
}
}
}
Mind you that they might want some special sort of response to (ie; not your full webpage), so you might do something like this after you're done parsing.
Response.Clear();
Response.ContentType = "text/plain";
Response.Write("Thanks!");
Response.End();
Update: this should be done in a Generic Handler (.ashx) file in order to avoid a great deal of overhead from the page model. Check out this article for more information about .ashx files
Use an IHttpHandler and avoid the Page model overhead (which you don't need), but use Request.Form to get the values so you don't have to parse name value pairs yourself. Just pretend you're in PHP or Classic ASP (or ASP.NET MVC, for that matter). ;)
I'd strongly recommend saving each request to some file.
This way, you can always go back to the actual contents of it later. You can thank me later, when you find that hostile-endian, koi-8 encoded, [...], whatever it was that stumped your parser...
Well if the incoming data is in a standard form encoded POST format, then using the Request.Form array will give you all the data in a nice to handle manner.
If not then I can't see any way other than using Request.InputStream.
If I'm reading your question right, I think you're looking for the InputStream property on the Request object. Keep in mind that this is a firehose stream, so you can't reset it.

Resources