0

Lets say I have an ASP.NET Web API which displays data result on the web browser, eg. {"Result": 10} when I run the application.

Is it possible for the result to be shown in a text file when I run the application?

Meaning when I run the application, a text file is created with the data {"Result": 10} in it. Or, the data is shown in the web browser and also a text file is created with the same data in it. Is that possible?

Susha Naidu
  • 307
  • 1
  • 3
  • 16
  • Which ASP.NET framework and version are you using? What have you tried? Where do you want the text file to be created? – CodeCaster Dec 19 '17 at 09:15
  • I looked through the question that i have been said to have duplicated before i posted this question. If i'm not wrong, is that generating a file that already exist? – Susha Naidu Dec 19 '17 at 09:20
  • Do you really need to create a local file? You can return the string directly to the browser without first saving it. Or you could avoid generating the string in the first place - this is a Json string. You can use `return Ok(myResult)` and have Web API serialize it, or `return Json(myResult);` to return it as Json explicitly. – Panagiotis Kanavos Dec 19 '17 at 09:22
  • If you really want to return a file, the duplicate is the correct answer. *You* will have to write the code that saves your string in a file first, although that's trivial `File.WriteAllText(somePath,myString)`. If you don't need that file though, use `OK()` or `Json()` – Panagiotis Kanavos Dec 19 '17 at 09:23
  • I want the text file to be created under desktop. So far i have done up to showing the output in web browser. Now i'm thinking if i can show the data that is shown in the web browser, in a text file too, as per the request of my supervisor – Susha Naidu Dec 19 '17 at 09:25
  • You cannot put files on a web site visitor's desktop. You can only offer files for download, the user has to decide where to save them. – CodeCaster Dec 19 '17 at 09:33
  • Ok that is true. If i follow the duplicate will i be able to get that? Or will i have to add somemore methods? – Susha Naidu Dec 19 '17 at 09:36

1 Answers1

2

Try to generate the response like this

HttpResponseMessage response = new HttpResponseMessage()
{
    Content = new StringContent(
                responseData,
                Encoding.UTF8,
                "text/plain"
            )
};

it will add header Content-type = text/plain in the response. This might help you.

Anup
  • 1,502
  • 2
  • 15
  • 31