我有一个 jquery 例程,它调用 MVC 操作,该操作将对 API url 执行 PUT/POST。来自 jQuery 的调用效果很好,并且与使用 C# 调用 API 一样有效。通过 Firebug/Fiddler 检查时,会从 API 收到 JSON 格式的响应。
如何将该响应发送回调用 jQuery?
我的 C# 代码是:
public string callAPIPut(string ApiUrl, string JsonString)
{
WebRequest request = WebRequest.Create(ApiUrl);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(JsonString);
request.ContentType = "application/json; charset=utf-8";
request.Method = WebRequestMethods.Http.Put;
request.ContentLength = JsonString.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, JsonString.Length);
newStream.Close();
return ""; // How do I return the JSON response from the API?
}
当执行 GET 时,我可以使用类似以下内容的方法来将响应返回给调用 jQuery:
response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
serviceResponse = sr.ReadToEnd();
}
return serviceResponse;
我不知道在进行 Put/Post 时如何返回响应?
最佳答案
public ActionResult CallAPIPut(string ApiUrl, string JsonString)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
byte[] data = Encoding.Default.GetBytes(JsonString);
byte[] result = client.UploadData(ApiUrl, "PUT", data);
return Content(Encoding.Default.GetString(result), "application/json");
}
}
或者通过包装自定义且可重用的操作结果来使其更加智能,以避免基础架构管道困惑您的 Controller :
public class ApiResult : ActionResult
{
public ApiResult(string apiUrl, string jsonData)
: this(apiUrl, jsonData, "PUT")
{
}
public ApiResult(string apiUrl, string jsonData, string method)
{
ApiUrl = apiUrl;
JsonData = jsonData;
Method = method;
}
public string ApiUrl { get; private set; }
public string JsonData { get; private set; }
public string Method { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
var contentType = "application/json";
response.ContentType = contentType;
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = contentType;
byte[] data = Encoding.Default.GetBytes(JsonData);
byte[] result = client.UploadData(ApiUrl, Method, data);
response.Write(Encoding.Default.GetString(result));
}
}
}
现在你的 Controller 操作就变成了:
public ActionResult CallAPIPut(string apiUrl, string jsonString)
{
return new ApiResult(apiUrl, jsonString);
}
关于c# - 从 MVC 放置/发布后如何获得 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11116611/