2017-09-02 95 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