2

API URL に対して PUT/POST を実行する MVC アクションを呼び出す jquery ルーチンがあります。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 に答える