简体   繁体   English

写入第三方API

[英]Writing to a 3rd party API

I am working in an asp.net application trying to write a JSON.Net query to write (POST) a record to an API. 我正在一个asp.net应用程序中尝试编写JSON.Net查询以将记录写入(POST)到API。 However, I am having trouble trying to figure out how to format the json string in order to pass it to the API. 但是,我无法弄清楚如何格式化json字符串以将其传递给API。

The "Example" on the vendor's support page has the following header information. 供应商支持页面上的“示例”具有以下标题信息。

POST /extact/api/profiles/114226/pages/423833/records HTTP/1.1
Host: server.iPadDataForm.com
Authorization: Bearer 6bfd44fbdcdddc11a88f8274dc38b5c6f0e5121b
Content-Type: application/json
X-IFORM-API-REQUEST-ENCODING: JSON
X-IFORM-API-VERSION: 1.1  

Question: 题:
If I am using JSON.Net, how do I get the header information passed to the API ? 如果我使用的是JSON.Net,如何将标头信息传递给API? I have looked at json.net website , but nothing has worked yet. 我看过json.net网站 ,但还没有任何工作。

JSON.NET is library for serializing and deserializing .NET objects to JSON. JSON.NET是用于将.NET对象序列化和反序列化为JSON的库。 It has nothing to do with sending HTTP requests. 它与发送HTTP请求无关。 You could use a WebClient for this purpose. 您可以使用WebClient来实现此目的。

For example here's how you could call the API: 例如,您可以在此处调用API:

string url = "http://someapi.com/extact/api/profiles/114226/pages/423833/records";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer 6bfd44fbdcdddc11a88f8274dc38b5c6f0e5121b";
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    client.Headers["X-IFORM-API-REQUEST-ENCODING"] = "JSON";
    client.Headers["X-IFORM-API-VERSION"] = "1.1";

    MyViewModel model = ...
    string jsonSerializedModel = JsonConvert.Serialize(model); // <-- Only here you need JSON.NET to serialize your model to a JSON string

    byte[] data = Encoding.UTF8.GetBytes(jsonSerializedModel);
    byte[] result = client.UploadData(url, data);

    // If the API returns JSON here you could deserialize the result
    // back to some view model using JSON.NET
}

The UploadData method will send an HTTP POST request to the remote endpoint. UploadData方法将向远程端点发送HTTP POST请求。 If you want to handle exceptions you could put it in a try/catch block and catch WebException which is what this method could throw if for example the remote endpoint returns some non 2xx HTTP response status code. 如果你想处理异常,你可以将它放在try/catch块中并捕获WebException ,这是该方法可能抛出的,例如远程端点返回一些非2xx HTTP响应状态代码。

Here's how you could handle the exception and read the remote server response in this case: 以下是在这种情况下如何处理异常并读取远程服务器响应:

try
{
    byte[] result = client.UploadData(url, data);
}
catch (WebException ex)
{
    using (var response = ex.Response as HttpWebResponse)
    {
        if (response != null)
        {
            HttpStatusCode code = response.StatusCode;
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                string errorContent = reader.ReadToEnd();
            }
        }
    }
}

Notice how in the catch statement you could determine the exact status code returned by the server as well as the response payload. 请注意,如何在catch语句中确定服务器返回的确切状态代码以及响应有效负载。 You could also extract the response headers. 您还可以提取响应标头。

Use Web API or the MVC API. 使用Web API或MVC API。

If you want to know the difference. 如果你想知道差异。

http://encosia.com/asp-net-web-api-vs-asp-net-mvc-apis/ http://encosia.com/asp-net-web-api-vs-asp-net-mvc-apis/

ASP.NET Web API vs. ASP.NET MVC “APIs” by Dave Ward Dave Ward的ASP.NET Web API与ASP.NET MVC“API”

In Short the differences are: 总之,差异是:

Content negotiation Flexibility Separation of concerns 内容协商灵活性关注点分离

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM