What is the ASP.NET equivalent of setting a request attribute in Java? - asp.net

I have some functionality in the code behind, which after executing needs to forward the request to another page. I want to pass along data like you would by setting a request attribute in Java (i.e. - I don't want it in the query string of the redirected response). Is this possible with ASP.NET (c#)?

You can use Server.Transfer if you want to forward the request and keep all of the Request variables, or you can use Session.

Are you using ASP.NET Webforms or MVC? The following will redirect your request to a new page. You'll have to test and see if it forwards post data (I'm not sure). Now that you mention it, I don't think ASP.NET has a built in "forward:" request like java does. I think it just has "redirect" for security reasons. (Someone correct me if I'm wrong).
In Webforms:
try Response.Redirect("mynewpage").
In MVC:
at the completion of your action method return Redirect("mynewpage")
I don't know your use case, but it is generally not good practice to pass post data to a different page/request. Typically the posted action will take care of persistence, and then a GET request will be issued to the redirect page. If the redirected view needs access to the posted data, it should go to the persistence mechanism (DB) to retrieve it. This method is more secure, and generally better practice. This is a very general guideline, so use it as your needs allow.
HTH

Yes - See the reflection code at:
HttpModule to add headers to request
However - the question is - do you really want to use request headers? probably not. its a hack to use them. If you simply want to pass information, use the Context.Items dictionary to transfer your items between requests with Server.Transfer.

Depending on what you are doing and where your events are, you can also make use of Cross Page Postback.
See http://msdn.microsoft.com/en-us/library/ms178139.aspx
Otherwise, I'd go with vcsjones answer of Server.Transfer

Related

Which one is more secure between Response.Redirect or Server.Transfer on the same server?

I have been reading these two functions and am considering to pick up the one which is much more secure. I want to use Server.Transfer because it executes at the server side in a sense. Is it better to use?
Server.Transfer("myUrl.aspx?id=1");
or
Response.Redirect("myUrl.aspx?id=2");
Update:
My question is based on the client-side data security which comes from a previous page rather than a URL change.
tl;dr:
Neither Server.Transfer or Response.Redirect offers security advantages over the other. Strongly recommend not using Server.Transfer at all, as it is an anti-pattern of modern HTTP/web resource base paradigms, further explanation on that below. Use Response.Redirect and focus on authorization/identity for security concerns.
Neither offers more security than the other. The server/endpoint still allows HTTP/HTTPS requests, any request can be sent to the server by a malicious client.
You should prefer Response.Redirect over Server.Transfer. Server.Transfer is ASP.NET Web Forms "code smell". ASP.NET Web Forms has never respected HTTP, Restful, Stateless, resource request web paradigms, which is what the web is built on, obviously.
Server.Transfer is a very old method. Server.Transfer maintains the original URL in the browser. This can help streamline data entry for wizards, but it will also make for confusion when debugging.
Maintaining the original URL is also a perfect example of ASP.NET Web Forms doing what it wants, making life easier in the short term but impacting maintainability of the software in the long term. Maintaining the original URL is also a perfect example of going against the grain of HTTP/web protocols. It prevents the user from sharing the resource URL. And, even if you plan on that URL never being shared, there is always one use case where it is still always very helpful for the user/system/exception handling to be able to share the URL and it is to provide the correct place/resource the user is on, at a time of error or issue or even user question, for customer service/troubleshooting/debugging to better serve the user/customer/client.
Server.Transfer is an example of a shortcut. It has no security advantages, as the server/endpoints are exposed on port 80 to client requests whether responding with a different resource (Server.Transfer) or telling the client to redirect (Response.Redirect) and request another resource.
Regarding the "skipping" round trip advantage of Server.Transfer over Response.Redirect, it is a very small benefit considering that Server.Transfer is a web anti-pattern as I explained above. It guides developers to less elegant web systems architecture rather quickly as well.
Regarding the second parameter of Server.Transfer, perserveForm, setting perserveForm to True will maintain the form and query string and will still be available to the next page you are sending the user to but it is not advantageous enough to warrant use because it impacts long term maintainability of the web application.
perserveForm is also an anti-pattern to stateless, RESTful, resource based modern web applications/paradigms as I have been discussing above. If you need to maintain form state, across requests, it should be done on the client with local storage, it is not the responsibility of the server to maintain state for each client. perserveForm is yet another example of ASP.NET Web Forms, trying to make things easier for the developer in the short term but making code overly complex and difficult to maintain and debug in the long term.
Using Response.Redirect would be more secure if you use it like this:
if (!Request.IsLocal && !Request.IsSecureConnection)
{
if (Request.Url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
{
string sNonSchemeUrl = Request.Url.AbsoluteUri.Substring(Uri.UriSchemeHttp.Length);
// Ensure www. is prepended if it is missing
if (!sNonSchemeUrl.StartsWith("www", StringComparison.InvariantCultureIgnoreCase)) {
sNonSchemeUrl = "www." + sNonSchemeUrl;
}
string redirectUrl = Uri.UriSchemeHttps + sNonSchemeUrl;
Response.Redirect(redirectUrl);
}
}
As it converts an HTTP request to a secure HTTP request (HTTPS).
Both are equal to a security question...
Server.Transfer("myUrl.aspx?id=1");
Server.Transfer redirects from the server back end.
Response.Redirect("myUrl.aspx?id=2");
Response.Redirect comes to the front end, goes back to the back end, and redirects.
You can observe it if you debug both from the front and back end.

How to enable/use cross-origin resource sharing with MVC 3?

I want to submit a form using AJAX to a MVC 3 Controller.
The form and the controller are on two different domains, which is why i want to use CORS.
I have read that the following code should do the trick in ASP.NET:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
from http://enable-cors.org/#how-asp.net
Should this code go directly in the controller that takes the form data?
As far as i know, there has to be some exchange of data between the client posting data and the server, to determine wether CORS is enabled/supported or not, so i figure that the one line of code has to go somewhere else?
Thanks
This could go in the controller. Actually I would probably externalize it in a custom action filter to avoid repeating it in every controller action that needs to be invoked from a cross domain AJAX call. There are no additional steps necessary. Just make sure that your browser supports CORS because if it doesn't adding this line will have strictly no effect whatsoever.

Method to trick ASP.NET to process HTTP PUT as POST?

I have a web cam that can send an image via HTTP PUT to a web server. I'd like to process this in ASP.NET MVC, but it doesn't natively support PUT. Is there any way to trick it into treating the request as a POST? I'm looking to get the Request.Form and Request.Files properties populated.
ASP.NET MVC supports PUT requests by putting the HttpPut attribute on the action.
(In earlier versions you might need to use the AcceptVerbs attribute...)
Are you sure it doesn't support HTTP Put? I see that it is listed within the HttpVerbs Enumeration: http://msdn.microsoft.com/en-us/library/system.web.mvc.httpverbs.aspx
All you should have to do is ensure that you have decorated your action appropriately.
This does not appear to be possible. I've just used the Request.InputStream to read in a bitmap directly.

What's the easiest way to get a web request into C# code?

So... I've got an ASP.NET app. Let's assume I configure IIS to always point to the same file, index.aspx. Let's say I want to write all my code in C# and then return some HTML I generated in the C#. How do I do that?
Would I just have 1 file with 1 line of code,
<%# Page CodeBehind="mycode.cs"
Is it necessary to have such a "useless" file? I can't direct the request straight into the code-behind?
Secondly, where are some good tutorials on code-behinds? Specifically, I see this Page_Load event that I guess gets called automatically?
Are there other events? What are they?
Also, how would I access things like POST data, or the request URL?
How would I return a HTML response? Or a 404?
I'm seeing a lot of tutorials on "inline" ASP, but I don't really care about that.
Sounds like you want a generic handler. They are available in the New Item... dialog. This will give you a .ashx file where you can handle incoming web requests just like you would in your scenario, but in a cleaner way. Using these you can return any kind of HTTP response, including HTTP errors. You have full access to the HTTP context for POST data, URL parameters, cookies, etc. See more here.
Another alternative is to implement IHttpHandler yourself, although with generic handlers there isn't much point in going through the effort.
Are there other events? What are they?
There is a whole lot of Events available when you inherit from System.Web.UI.Page. You can see them http://msdn.microsoft.com/en-us/library/ms178472.aspx
Also, how would I access things like POST data, or the request URL?
this.Request.Form, would let you access the PostData from a page. this.Request.Url would let you access the url.
How would I return a HTML response? Or a 404?
You can override the Render method of the page to provide HTML Response. You can throw a HttpException(404, "file not found") to return 404.
After going through your questions, you most likely need ASP.NET MVC rather than ASP.NET webforms or you can use a handler as suggested by Martin

What is the difference between HttpHandler and a Web User Control and when to use each one?

I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong
Unfortunately your question is a little like "Should I use a sandwich or a cement mixer". HttpHandlers and User controls are completely different things.
HttpHandlers are used to process HTTP requests. For example, if you wanted to dynamically create an RSS feed, you could write an HTTP handler that handles all requests for ".rss" files, creates the output and sends it back to the user.
User controls are used within ASPX pages to encapsulate units of functionality that you want to re-use accross many pages.
Chances are, if you're using user controls successfully, you don't want to use HttpHandlers!
Basically a user control is a piece of server logic and UI. An HTTP Handler is only a piece of logic that is executed when a resource on your server is requested. For example you may decide to handle requests for images sent to your server through your own handler and serve images from a database instead of the file system. However, in this case there's no interface that the user sees and when he visits a URL on your server he would get the response you constructed in your own handler. Handlers are usually done for specific extensions and HTTP request types (POST, GET). Here's some more info on MSDN: http://msdn.microsoft.com/en-us/library/ms227675(VS.80).aspx
Expect a better answer (probably before I finish typing this) but as a quick summary.
A user control is something that can be added to a page.
A HttpHandler can be used instead of a page.
Just to clarify the question. I was reading the Hanselman post
http://www.hanselman.com/blog/CompositingTwoImagesIntoOneFromTheASPNETServerSide.aspx
and thinking that I would never solved the problem with a HttpHandler, maybe with a simple page returning a binary content.
This led me to think that I should add HttpHandler to my developer tool belt.
Even an Asp.Net page is an HttpHandler.
public class Page : TemplateControl, IHttpHandler
A user control actually resides within the asp.net aspx page.

Resources