简体   繁体   English

如何在客户端设置请求主体

[英]How to set the request body on the client side

Suppose I have the following web method using C# and .NET: 假设我有以下使用C#和.NET的Web方法:

[WebInvoke(UriTemplage="/users", Method="POST")]
[OperationContract]
public User AddNewUser(User u);

It is expected that when you implement POST web method you will accept a request body as part of the incoming HTTP request message. 预期在实现POST Web方法时,您将接受请求正文作为传入HTTP请求消息的一部分。 The parameter u is expected to be deserialized from the incoming HTTP message body. 预计将从传入的HTTP消息正文中反序列化参数u。

My question is: how do we set this request body on the client side ? 我的问题是:我们如何在客户端设置此请求正文? It's got to be set somewhere. 它必须放在某个地方。 It really confuses me. 这真的让我感到困惑。

Besides if I added "ResponseFormat = WebMessageFormat.Json" to WebInvoke, how can I deserialize from the returned json string into the User object ? 此外,如果我在WebInvoke中添加了“ ResponseFormat = WebMessageFormat.Json”,如何将返回的json字符串反序列化为User对象?

Thanks. 谢谢。

Your question doesn't reveal what you have tried. 您的问题并未透露您尝试过的内容。 If you are using .net on the client then you can use the DataContractSerializer to get the serialized data. 如果在客户端上使用.net,则可以使用DataContractSerializer获取序列化的数据。

You can then use an HttpWebRequest with the method set to POST . 然后,您可以将HttpWebRequest的方法设置为POST Add the serialized data to the web request and use the GetResponse() method. 将序列化的数据添加到Web请求中,并使用GetResponse()方法。

Alternatively you could use Fiddlr to test your web service using requests that you create. 另外,您可以使用Fiddlr使用创建的请求来测试Web服务。 It gives you a concise view of exactly what is going up to the server. 它为您提供了有关服务器运行情况的简明视图。

To perform a POST request to your WCF Rest method: 向WCF Rest方法执行POST请求:

    private string UseHttpWebApproach<T>(string serviceUrl, string resourceUrl, string method, T requestBody)
    {
            string responseMessage = null;                
            var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
            if (request != null)
            {
                request.ContentType = "application/json";
                request.Method = method;
            }

            if(method == "POST" && requestBody != null)
            {                   
                byte[] requestBodyBytes = ToByteArrayUsingJsonContractSer(requestBody);                
                request.ContentLength = requestBodyBytes.Length;
                using (Stream postStream = request.GetRequestStream())
                    postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
            }

            if (request != null)
            {
                var response = request.GetResponse() as HttpWebResponse;
                if(response.StatusCode == HttpStatusCode.OK)
                {
                    Stream responseStream = response.GetResponseStream();
                    if (responseStream != null)
                    {
                        var reader = new StreamReader(responseStream);

                        responseMessage = reader.ReadToEnd();
                    }
                }
                else
                {
                    responseMessage = response.StatusDescription;
                }
            }
            return responseMessage;
    }

    private static byte[] ToByteArrayUsingJsonContractSer<T> (T requestBody)
    {
        byte[] bytes = null;
        var serializer1 = new DataContractJsonSerializer(typeof(T));
        var ms1 = new MemoryStream();
        serializer1.WriteObject(ms1, requestBody);
        ms1.Position = 0;
        var reader = new StreamReader(ms1);
        bytes = ms1.ToArray();
        return bytes;
    }

Now Assuming your User object as shown below: 现在假设您的User对象如下所示:

Public Class User
{
    Public int UserId  {get;set;}
    Public string UserName {get;set;}
    Public string Password  {get;set;}
}

The to call the above method i do: 调用上面的方法我做:

User objUser = new objUser();
objUser.Username = "Test";
objUser.Password = "Test";
UseHttpWebApproach<User>(serviceBaseUrl, "users", "POST", objUser);

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

相关问题 如何使用C#为Simple.OData.Client创建条目请求设置主体? - How to set the body for a Simple.OData.Client create entry request using C#? 如何从客户端设置HTMLEditorExtender HTML - How to set HTMLEditorExtender HTML from client side 如何获取响应正文以及如何使用 HttpURLConnection 类设置请求正文? - How to get the response body and how to set the request body with HttpURLConnection class? 如何使用httpWebRequest设置请求体 - how to set up request body with httpWebRequest 如何记录来自客户端的完整的原始WCF客户端请求? - How to log full raw WCF client request from client side? 如何使用 http 客户端在 Postman 中添加以下请求正文(字符串)? - How to add below request body (string) in Postman using http client? 如何在c#的客户端请求中插入此soap标头 - how can insert this soap header in client side request at c# 如何获取由jQuery分配或设置的标签值 - How to get label value which is assigned or set client side by jQuery 如何在客户端将Json数据设置为camelCase一次 - How to set Json data to camelCase once on the client side 如何在C#中的GraphQL Client端点的请求主体中发送oauth_token和client_id - How to send oauth_token and client_id in the request body of GraphQL Client endpoint in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM