2017-09-02 127 views
1

爲什麼我不能返回Json。它被加下劃線並且在當前情況下不存在。未識別Json類型

using System; 
using System.Collections.Generic; 
using System.Net; 
using System.Net.Http; 
using System.Text; 
using System.Threading.Tasks; 
using System.Web.Http; 
using System.Web.Http.Results; 
using System.Web.Mvc; 

//class and namespace detail removed to keep this post short 

    public async Task<IHttpActionResult> Post(string url, StringContent data, Dictionary<string, string> headers) 
    { 
     using (var client = new HttpClient()) 
     { 
       var response = await client.PostAsync(url, data); 
       var result = await response.Content.ReadAsStringAsync(); 

       //the line below is the error******** 
       return Json(new { HttpStatusCode = HttpStatusCode.OK }); 
     } 
    } 

我也試過install-package System.Json,這並沒有幫助。

我知道有可能是其他的東西錯了,因爲我在一個小時前開始,但從未工作過的代碼,我不明白爲什麼Json無法識別

這是從類庫中(如果有關係)

+0

該方法是任何類或命名空間之外定義!? –

+0

@PeterBons,對不起。不,我只是刪除了,以保持短小。更新以清楚說明。對不起 – MyDaftQuestions

回答

2

該方法是Web API的ApiController的輔助方法,應在ApiController派生類中調用。

public class MyApiController : System.Web.Http.ApiController { 

    public async Task<IHttpActionResult> Post(string url, StringContent data, Dictionary<string, string> headers) { 
     using (var client = new HttpClient()) { 
      var response = await client.PostAsync(url, data); 
      var result = await response.Content.ReadAsStringAsync(); 

      return Json(new { HttpStatusCode = HttpStatusCode.OK }); 
     } 
    }  
} 

同樣存在對MVC Controller派生類以及

public class MyController : Controller { 

    public async Task<ActionResult> Post(string url, StringContent data, Dictionary<string, string> headers) { 
     using (var client = new HttpClient()) { 
      var response = await client.PostAsync(url, data); 
      var result = await response.Content.ReadAsStringAsync(); 

      return Json(new { HttpStatusCode = HttpStatusCode.OK }, JsonRequestBehavior.AllowGet); 
     } 
    }  
} 
+0

啊,我想我可以返回內容,如果我從控制器然後繼承? – MyDaftQuestions

+0

@MyDaftQuestions'Controller'也有一個'Json'輔助方法。你應該更新你的問題,以明確你正在做的事情。這個假設是Web API,因爲你的例子中使用了類型。 – Nkosi