Hello everyone,
I have a web service in which I am manipulating POST and GET methods to facilitate upload / download functionality for some files in a client/server style architecture. Basically the user is able to click a button to download a specific file, make some changes in the app, then click upload button to send it back.
Problem I am having is with the download. Say the user expects 3 files 1.txt, 2.txt and 3.txt. Except 2.txt does not exist on the server.
So I have code like (on server side):
public class HttpHandler : IHttpHandler
{
public void ProcessRequest
{
if (context.Request.HttpMethod == "GET")
{
GoGetIt(context)
}
}
private static void GoGetIt(HttpContext context)
{
var fileInfoOfWhereTheFileShouldBe = new FileInfo(......);
if (!fileInfoOfWhereTheFileShouldBe.RefreshExists())
{
//Remove this line below
//throw new Exception("Oh dear the file doesn't exist");
//Replace with a force return of whichever code I chose e.g. 200
??...
}
...
So the problem I have is that when I run the application, and I use a WebClient on client side to use DownloadFile method which then uses the code I have above, I get:
WebException was unhandled: The remote server returned an error: (500) Internal Server Error.
(While debugging) If I attach to the browser and use http://localhost:xxx/1.txt
I can step through server side code and throw the exception as intended. So I guess I'm wondering how I can handle the internal server error on the client side properly so I can return something meaningful like "File doesn't exist". One thought was to use a try catch around the WebClient.DownloadFile(address, filename)
method but i'm not sure thats the only error that will occur i.e. the file doesn't exist.
edit: following the solution using HttpResponse
So if I were to use HttpResponse, could I get some suggestions as how to start?
I remove the exception throw from the client side, and replace with custom HttpResponse? So basically I guess I would chose a code to use, say 200, and force return code 200 in that if statement above. See comment.
Then on client side just use If (Response.StatusCode == 200)
and do whatever I want to do (inform user file doesn't exist )
I'm along the right lines?
edit 2:
I've been trying using a try catch around my file copy methods, then in the catch, setting the status code or status description but this throws exceptions when setting the status description.. like this:
context.Response.StatusDescription = ex.ToString();
context.Response.Status = ex.ToString();
ArgumentOutOfRangeException - specified argument was out of the range of valid values.