【问题标题】:How to receive a JSON body in C# MVC (no ajax)如何在 C# MVC 中接收 JSON 正文(无 ajax)
【发布时间】:2017-08-25 13:55:31
【问题描述】:

我有一个客户端正在向我的 asp.net mvc 应用程序发送一个 json。我在哪里可以收到 json 正文?

发送:

        var client = new RestClient(uri);
        client.Authenticator = new NtlmAuthenticator();

        RestRequest requestCom =
            new RestRequest("", method);

        //add headers
        requestCom.AddHeader("Accept", "application/json");

        if (body != null)
        {
            requestCom.AddJsonBody(body);
        }

        IRestResponse response = client.Execute(requestCom);

控制器:

    public string Index([FromBody]object body)
    {
        return body.ToString();
    }

url 是我在 mvc 应用程序中的控制器。那么如何接收尸体呢?

【问题讨论】:

标签: c# json asp.net-mvc restsharp


【解决方案1】:

假设你有一个这样的模型

public class MyModel {
    public string AProperty { get; set; }
}

并发送到服务器

var client = new RestClient(uri);
client.Authenticator = new NtlmAuthenticator();

var requestCom = new RestRequest("", method);
//add headers
requestCom.AddHeader("Accept", "application/json");

var body = new MyModel {
    AProperty = "Hello World!!!"
}

if (body != null) {
    requestCom.AddJsonBody(body);
}

IRestResponse response = client.Execute(requestCom);

Controller 动作必须期待 body 中的模型

public string Index([FromBody]MyModel body) {
    return body.ToString();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2019-11-13
    • 2021-08-10
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多