简体   繁体   English

使用C#ASP.NET MVC异步将JSON字符串发布到RESTful API

[英]Post JSON string to RESTful API using C# ASP.NET MVC async

I'm having trouble with sending a post request to a RESTful API. 我在将发布请求发送到RESTful API时遇到问题。 The API expects the following JSON body: 该API需要以下JSON正文:

{ "APIKey":"String content", "ID":"String content", "Data":"String content", "TokenScheme":0 } {“ APIKey”:“字符串内容”,“ ID”:“字符串内容”,“ Data”:“字符串内容”,“ TokenScheme”:0}

I'd like for it to use async but this is a first for me and I'm having issues just handling the return string. 我希望它使用异步,但这对我来说是第一次,而且在处理返回字符串时遇到了问题。 I'd just like to know how to send the string data to the view and I'll get it from there. 我只想知道如何将字符串数据发送到视图,然后从那里获取它。

Here is what I'm trying to use but the browser just spins and spins. 这是我要使用的内容,但浏览器只会旋转。

public async Task<string> RunAsync()
{
    using (var client = new HttpClient())
    {
        // TODO - Send HTTP requests
        client.BaseAddress = new Uri("https://test-api.com/Services.svc/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        string APIKey, ID, Data, Scheme;

        // HTTP POST
        string[] jsonRequest = { APIKey = "", ID = "", Data = "teststring", Scheme = "0" };
        //alt option IHttpActionResult 
        HttpResponseMessage response = await client.PostAsJsonAsync("REST/Service", jsonRequest);
        if (response.IsSuccessStatusCode)
        {
            Debug.WriteLine(@"             successful.");
            return "";
        }
        else
        {
            Debug.WriteLine(@"             Failed.");
            return "";
        }
    }
}

You are mixing two concepts here. 您在这里混合了两个概念。 A string array does not have property name or indexors, only a set of strings. 字符串数组没有属性名称或索引器,只有一组字符串。 You mistakenly seem to do that by also assigning values to variables on the same line where you are creating the array. 您似乎错误地通过在创建数组的同一行上还给变量赋值来做到这一点。

So this line: 所以这行:

string[] jsonRequest = { APIKey = "", ID = "", Data = "teststring", Scheme = "0" };

Actually is doing this: 实际上是这样做的:

APIKey = "";
ID = "";
Data = "teststring";
Scheme = "0";

string[] jsonRequest = { "", "", "teststring", "0" }; // String array without property names

Easiest way to fix your problem is to use an anonymous type instead of a string[] 解决问题的最简单方法是使用匿名类型而不是字符串[]

var jsonRequest = new { APIKey = "", ID = "", Data = "teststring", Scheme = "0" };

The new object will have named properties: 新对象将具有命名属性:

if (jsonRequest.Data == "teststring") // returns true.

the json should not be declared as a string[]. json不应声明为string []。 That will create a Json like 这将创建一个像

[{ "APIKey":"String content"}, 
{"ID":"String content"}, 
{"Data":"String content"}, 
{"TokenScheme":0 }]

you want to just create an anonymous object and pass it to the PostAsJsonAsync 您只想创建一个匿名对象并将其传递给PostAsJsonAsync

like this 像这样

var anonymousObject = new { APIKey = "", ID = "", Data = "teststring", TokenScheme = "0" };

HttpResponseMessage response = await client.PostAsJsonAsync("REST/Service", anonymousObject);

PostAsJsonAsync will handle serializing your object to Json for you. PostAsJsonAsync将为您处理将对象序列化为Json的过程。

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

相关问题 将JSON对象发布到C#ASP.NET WEB API - POST JSON object to C# ASP.NET WEB API How to parse SQL JSON string in C# in asp.net mvc web api? - How to parse SQL JSON string in C# in asp.net mvc web api? 使用 C# 反序列化 API Json 时出错 - Z9E0DA8438E1E38A1C30F4B76CE7 Core - Error in Deserializing the API Json using C# - ASP.NET Core MVC 如何使用 MongoDB 将动态 JSON 属性发布到 C# ASP.Net Core Web API? - How to post a dynamic JSON property to a C# ASP.Net Core Web API using MongoDB? C# ASP.NET MVC 使用 JSON 将字符串转换为列表 - C# ASP.NET MVC convert string to list using JSON 使用 C# HttpClient,如何将字符串 HttpContent POST 到 ASP.net Core Web API? - Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API? 使用ASP.NET MVC 2和C#打印文档或字符串 - Printning document or string using ASP.NET MVC 2 and C# 使用 HTTP Post(RESTful API)将来自 React.JS 前端的请求传递到 C# 后端(ASP.NET) - Passing a Request from React.JS front-end to C# back-end (ASP.NET) using HTTP Post (RESTful API) C# - 我的 ASP.NET MVC 页面总是返回 null 给我的 Z0ECD11C1D7A2874201D148A23BBD7A - C# - my ASP.NET MVC page always returns null to my JSON POST request 如何在ASP.Net Core MVC模型中使用C#从rest api解析json数据并将其显示在HTML页面上 - how to parse json data from a rest api using C# in the ASP.Net Core MVC model and display it on a HTML page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM