2017-12-21 3 views
1

私はいくつかのデータを含むtxtファイルを持っています。私はウェブブラウザがtxtファイルにデータを表示することを可能にするいくつかのコードを持っています。データをJSON形式で表示したい。ここでJSONで返されたときにファイル内のデータがWebブラウザに表示されない

は私のコードは、私はreturn result;を行うと

FileReaderClient.cs

public class FileReaderClient : IHttpActionResult 
{   
    public string filePath;  
    public FileReaderClient(string filePath) 
    { 
     this.filePath = filePath;   
    } 
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
    { 
     return Task.Run(() => 
     { 
      var response = new HttpResponseMessage(HttpStatusCode.OK) 
      { 
       Content = new StreamContent(File.OpenRead(filePath)) 
      }; 

      return response; 
     }); 
    } 
} 

FileReaderController.cs

public IHttpActionResult Get() 
    { 
     var result = new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\testfile.txt"); 
     return result; 
    } 

私はで表示私のtxtファイル内のデータを取得していますウェブブラウザ。しかし、私はJSON形式で返すと、return Json(result);、私は{"filePath":"C:\\Users\\attsuap1\\Desktop\\testfile.txt"}私のtxtファイルのデータの代わりに結果を取得します。どうしてこんなことに?そして、WebブラウザでJSON形式のtxtファイルにデータを表示するにはどうすればよいですか?

誰かが私を助けてくれてありがとうございました。

+0

私はしかし、それがソリューションエクスプローラに表示されていませんが、そのOKですファイルフォルダを作成し –

答えて

2

あなたは..youがServer.MapPath機能でファイルにアクセスする必要が物理パスとファイルにアクセスしようとしているので、あなたがエラーに直面している

[HttpGet]//http get as it return file 
     public HttpResponseMessage GetTextFile() 
     { 
      //below code locate physcial file on server 
      var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.txt"); 
      HttpResponseMessage response = null; 
      if (!File.Exists(localFilePath)) 
      { 
       //if file not found than return response as resource not present 
       response = Request.CreateResponse(HttpStatusCode.Gone); 
      } 
      else 
      { 
       string data = string.Join(" ", File.ReadAllLines(localFilePath)); 
       response = new HttpResponseMessage 
       { 
        StatusCode = HttpStatusCode.OK, 
        Content = new StringContent(data, Encoding.UTF8, "text/html") 
       }; 
      } 
      return response; 
     } 

応答としてバックファイルの内容を送信するために、以下のようにしてみてください。..あなたはwebpiやWebアプリケーションを使って作業しています。

このようにするには、webAPIにフォルダを作成し、そのフォルダにファイルを保存します。例えば

string pathToFiles = Server.MapPath("~/files/testfile.txt"); 

はここをチェック:https://www.dotnetperls.com/mappath

+0

あなたのために働いたかを私は提案の方法を試してみて、私に知らせてくださいすることができます?私は百万回を更新しました –

+0

@SushaNaidu - コード –

+0

で与えられたように詳細を送信しようとするこれらのコードはすべてコントローラまたはFileReaderClient.csの下にありますか? –

関連する問題