为什么我不能归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 :(得分: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);
}
}
}