Json类型未被识别

时间:2017-09-02 13:13:50

标签: c# asp.net-mvc asp.net-web-api

为什么我不能归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无法识别

这是来自一个类库(如果重要)

1 个答案:

答案 0 :(得分: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);
        }
    }    
}