How to post JSON to a server using C#?

后端 未结 13 1613
臣服心动
臣服心动 2020-11-22 05:55

Here\'s the code I\'m using:

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.Protoco         


        
13条回答
  •  抹茶落季
    2020-11-22 06:28

    WARNING! I have a very strong view on this subject.

    .NET’s existing web clients are not developer friendly! WebRequest & WebClient are prime examples of "how to frustrate a developer". They are verbose & complicated to work with; when all you want to do is a simple Post request in C#. HttpClient goes some way in addressing these issues, but it still falls short. On top of that Microsoft’s documentation is bad … really bad; unless you want to sift through pages and pages of technical blurb.

    Open-source to the rescue. There are three excellent open-source, free NuGet libraries as alternatives. Thank goodness! These are all well supported, documented and yes, easy - correction…super easy - to work with.

    • ServiceStack.Text - fast, light and resilient.
    • RestSharp - simple REST and HTTP API Client
    • Flurl- a fluent, portable, testable HTTP client library

    There is not much between them, but I would give ServiceStack.Text the slight edge …

    • Github stars are roughly the same.
    • Open Issues & importantly how quickly any issues closed down? ServiceStack takes the award here for the fastest issue resolution & no open issues.
    • Documentation? All have great documentation; however, ServiceStack takes it to the next level & is known for its ‘Golden standard’ for documentation.

    Ok - so what does a Post Request in JSON look like within ServiceStack.Text?

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

    That is one line of code. Concise & easy! Compare the above to .NET’s Http libraries.

提交回复
热议问题