简体   繁体   English

如何将POST json从C#发送到asp.net Web API

[英]how to send POST json from C# to asp.net web api

How is it possible to make a POST request to ASP.Net web api from C#. 如何从C#向ASP.Net Web API发出POST请求。 I have used Newtonsoft dll files to create the json, but, I am not able to send it to the api. 我已经使用Newtonsoft dll文件创建了json,但是我无法将其发送到api。

My code is : 我的代码是:

        Login login = new Login
        {
            userid = username.Text,
            pass = pass.Text
        };
        string json = JsonConvert.SerializeObject(login, Formatting.Indented);

How to send this json to web api, and get a response ? 如何将此json发送到Web API,并获得响应?

Edit 编辑

string url = "myurl";


        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json; charset=utf-8";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {

            json = json.Replace("\r\n","");
            //json = json.Replace("\",", "\","   + "\"" +"\u002B");
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            pass.Text = result.ToString();
        }

I made it work, by having a few edits. 通过进行一些编辑,我使它起作用。 Instead of directly serializing the json object, I used a class, and assigned values to it, and serialized it using JavaScriptSerializer. 我没有直接序列化json对象,而是使用了一个类,并为其分配了值,然后使用JavaScriptSerializer对其进行了序列化。 Thanks for your help Shekhar. 感谢您的帮助Shekhar。

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json; charset=utf-8";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string loginjson = new JavaScriptSerializer().Serialize(new
            {
                userid = username.Text,
                password = pass.Text
            });

            streamWriter.Write(loginjson);
            streamWriter.Flush();
            streamWriter.Close();

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                pass.Text = result.ToString();
            }
        }

You can use HttpWebRequest class to create a request and use StreamWriter to write your Json with the request and finally get HttpWebResponse from the Web API. 您可以使用HttpWebRequest类创建请求,并使用StreamWriter用请求编写Json并最终从Web API获取HttpWebResponse

var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
   streamWriter.Write(json);
   streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

Reg: "How to send this JSON to Web API, and get a response?" Reg:“如何将此JSON发送到Web API并获得响应?”

The current existing answers to your question all use .NET's WebRequest ; 您问题的现有答案均使用.NET的WebRequest which is a super frustrating library to work with. 这是一个超级令人沮丧的库。 I would like to offer the easiest & most concise way of 'sending JSON to Web API'. 我想提供“将JSON发送到Web API”的最简单,最简洁的方法。

Open-source to the rescue. 开源拯救。 There are three excellent open-source, free NuGet libraries as alternatives. 有三种出色的开源免费NuGet库可供选择。 Thank goodness! 谢天谢地! These are all well supported, documented and easy to work with. 这些都得到了很好的支持,记录和易于使用。

There is not much between them, but I would give ServiceStack.Text the slight edge … 它们之间没有太多,但是我会给ServiceStack.Text带来一点优势……

  • Github stars are roughly the same. Github的星星大致相同。
  • Open Issues & importantly how quickly any issues closed down? 未解决的问题,重要的是,任何问题关闭的速度如何? ServiceStack takes the award here for the fastest issue resolution & no open issues. ServiceStack凭借最快的问题解决速度和无公开的问题在这里获奖。
  • Documentation? 文档? All have great documentation; 所有人都有很好的文档。 however, ServiceStack takes it to the next level & is known for its 'Golden standard' for documentation. 但是,ServiceStack将其提升到一个新的水平,并以其“黄金标准”而闻名。

Ok - so what does a Post Request in JSON look like within ServiceStack.Text? 好的-在ServiceStack.Text中,JSON中的Post Request看起来如何?

var response = "http://example.org/login"
    .PostJsonToUrl(new Login { Userid="admin", Password="mypassword" });

That is one line of code. 那是一行代码。 Concise & easy! 简洁易用! Compare the line of code to the overly complicated WebRequest 将代码行与过于复杂的WebRequest进行比较

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

相关问题 ASP.NET Core Web API如何从客户端C#发送json对象 - asp.net core web api how to send json object from client side c# 将JSON对象发布到C#ASP.NET WEB API - POST JSON object to C# ASP.NET WEB API 如何使用 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? asp.net 核心 3 Web Api ! 将 json 发送到 POST 操作 - asp.net core 3 Web Api ! send json to POST Action ASP.NET C#REST WEB API-POST多个JSON值 - ASP.NET C# REST WEB API - POST Multiple JSON values 从 ASP.NET MVC 项目后面的 C# 代码向另一个 web 站点发送 JSON 请求 - Send a JSON request to another web site from C# code behind in an ASP.NET MVC project 如何使用ASP.NET C#发送和接收Web API的答案 - How to send and receive answers to a web api using ASP.NET C# 如何在C#中使用HttpClient将对象正确发布到ASP.NET Web API? - How do I correctly POST an object to ASP.NET Web API using HttpClient in C#? 使用 C# HttpClient,如何将字符串 HttpContent POST 到 ASP.net Core Web API? - Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API? 从Angular将Json对象解析为C#ASP.Net Core Web API - Parse Json object from Angular to C# ASP.Net Core Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM