2

我有一个调用 MVC 操作的 jquery 例程,该操作将对 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 时如何返回响应?

4

2 回答 2

4
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");
    }
}

或者通过包装自定义和可重用的操作结果来使其更智能,以避免基础设施管道使您的控制器混乱:

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));
        }
    }
}

现在你的控制器动作就变成了:

public ActionResult CallAPIPut(string apiUrl, string jsonString)
{
    return new ApiResult(apiUrl, jsonString);
}
于 2012-06-20T09:55:39.433 回答
0
 Stream newStream = request.GetRequestStream();
 newStream.Write(data, 0, JsonString.Length);
 newStream.Close();

您将 JSON 发布到服务器。要获取 JSON,您需要发布/放置并使用 ResponseStream 来读取服务器返回的数据。

一个样品:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create (
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Clean up the streams and the response.
            reader.Close ();
            response.Close ();
        }
    }
}

来自http://msdn.microsoft.com/en-us/library/456dfw4f.aspx的示例

编辑:您将返回 responseFromServer 并在您的 Javascript 回调中使用它。

于 2012-06-20T09:49:26.180 回答