Getting the content of a .aspx file in a .cs class - c#

What's a good method for getting the content of a .aspx web page as a String. This is from a C# Class which is compiled and deployed to the same machine.
Should I use a HTTP request? Or is there a means of doing the same through a file path, and would this trigger the code behind of the page?

If you use HTTP request, like WebClient and use WebClient.DownloadString(#"http://someSite/somepage.aspx"), that would trigger the server side code and you will get HTML generated by the server. Not the actual aspx page.
But if you use File.ReadAllLines('somepage.aspx') from your current project then you will get the file contents and it will not trigger the server side code. But you can only do that from your current project. You can't access an aspx page over http

This code retrieves the root directory that is hosting the application in IIS. Then, it concatenates the filename. Finally, it reads the contents into a string variable.
Reading a file from disk does not trigger the code-behind; only a request through the ASP.NET pipeline does that.
string path = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Index.aspx");
string fileContents = File.ReadAllText(path);

An HTTP request would usually not return the content of the aspx file since the server should interpret it (take this with a grain of salt, it all depends on your server and how its configured, maybe you've got a special setup)
If you want to read the content of the aspx file, open the file using its location on the disk. It won't trigger the code behind the page since this is triggered by the web server and you're not using it using a file path
if you want to read the output produced when the aspx file is read, open the url to this file. It will trigger the backing code and you will received the output.

Related

C# windows service: HTML page with picture, CSS and JS as a response

I am learning to build a windows service, but it takes requests (e.g. localhost:8081/index) from the browser to. Therefore, the HTTP response should contain an HTML page.
The HTML page looks okay when I double click the index.html file, but it lost all the CSS and js files when I request from the web browser. And I open the developer's tool in chrome and found out that all the CSS and JS files were corrupted and contain the code from my HTML page (weird).
I used HttpListenerContext class to listen for http://localhost/index request, and then open index.html file and used File.ReadAllBytes(file). When composing the response, I used the following code:
responseBytes = File.ReadAllBytes(file);
response.ContentLength64 = responseBytes.Length;
await response.OutputStream.WriteAsync(responseBytes, 0, responseBytes.Length);
response.OutputStream.Close();
Can anyone help me to figure out why this is happening?
So I figured out the answer by myself when I traced the code. When request localhost/index comes in from the browser, the GET method will first acquire index.html first, then there are other GET requests come in for the CSS, image and JS as well (It's weird that I didn't see the later requests before.)
Then I updated the handler to compose responses contains CSS, image and JS files. Everything works perfectly now.

How do I create a link to a file I have saved as a memory stream in a SQL table?

My web application (C# and ASP.Net) allows someone to upload a jpg/pdf file and save it as a memory stream inside a SQL table. This is what it looks like once written in the table:
0xFFD8FFE000104A4649.....
Now I want to provide this file back on my web interface through a link where the user can download this file. I have retrieved my file by converting the string above back to a byte array using
filedata = Encoding.ASCII.GetBytes(<string above>);
Then I called this:
string filename = "pic.jpg";
File.WriteAllBytes(filename, filedata);
But I have no clue how I should post this back to the user as a downloadable link on my web interface. Do I have to save this file to a temporary folder on my server or is there a way that I could invoke a call to render my file back as a picture where the user will be prompted to save the file or open it?
Thank you!
You will need to create a page / action / function that writes the bits back as the response to an HTTP request. Keep in mind that in doing so you will probably need to set the proper Content-Type header in the response according to what your file is.
So, you generate a link that calls your page / action / function. Then That sends the binary data back in an HTTP response. Something like
pic.jpg
If you some detail as to what framework you're using (MVC, WebForms, etc) then we can give more detailed examples.
Depending on how you want to present the image.
If you want to embed the image in the web return an link to the file with
string filename = Path.Combine(HttpRuntime.AppDomainAppPath, "Content/Images/pic.jpg");
File.WriteAllBytes(filename, filedata);
return filename;
then in the JavaScript side create an img element with thatsrc
Or if you want the user to download the file do what #squillman says in his answer

Download from url that generates a file

I need to be able to download a file from url. The url does not link to an actual file instead it generates the file on the server first and then gives a download dialog. Probably returning an mvc FileResult.
I'm just interested in getting the byte[] from the file.
I've tried:
using (var webClient = new WebClient())
{
System.Uri uri = new System.Uri(Document.Url);
bytes = await webClient.DownloadDataTaskAsync(uri);
}
This works but I get a corrupted file as expected.
I do not have control over how the server generates or serves the file.
Any way to wait for the file to complete generating and then get the file content?
TIA
Never mind. Turns out the link returns some javascript that auto authenticates a user and then does a jquery get to another url and port to generate the file. So I was basically downloading that script and saving it to pdf. doh.
So a work around would be to mimic that in some way.

How to respond to a GET file request?

I want some external client to search in one specific directory of my ASP.NET website for a specific file, and that file should be generated (and given to the client) when the user makes a request.
Is it possible? Which method should I use to program this response?
Yes, you could build an ASPX page for example that created the file on Page_Load and then set the byte[] of that file to the Response of the page.
... Page_Load(...)
{
// create the file
// set the response
Response.WriteFile(pathToNewFile);
}

Use HTML string from Server Requets, and create the web page without saving it a file [in C#]

I´m sending the value of a variable via POST to a PHP page in C#. I get the data stream from the server that has all the web page in HTML with the value of the POST. This information is stored in a string variable.
I would like to open a browser and show the web page (maybe using System.Diagnostics.Process.Start("URL")), without having to save it in a file, this is showing the page in the moment and, when the browser is closed, no file is stored in the server.
Any idea?
Drop a WebBrowser control into a new form webBrowser1 and set its DocumentTextProperty to your result html
webBrowser1.DocumentText = ("<html><body>hello world</body></html>");
source:
<html><body>hello world</body></html>
You aren't going to be able to do that in an agnostic way.
If you simply wanted to open the URL in a browser, then using the Process class would work.
Unfortunately, in your case, you already have the content from creating the POST to the server, and you really want to stream that response in your application to the browser.
It's possible among the some browsers, but it's not able to be done in an agnostic way (and it's complicated even when targeting a specific browser).
To complicate matters, you want the browser to believe that the stream you are sending it is really coming from the server, when in reality, it's not.
I believe that your best bet would be to save the response to the file system in a temp file. However, before you do, add the <base> tag to the file with the URL that the file came from. This way, relative URLs will resolve correctly when rendered in the browser.
Then, just open the temporary file in the browser using the Process class.

Categories