【问题标题】:WCF restful service: How to send long string parameters in POST requests?WCF RESTful 服务:如何在 POST 请求中发送长字符串参数?
【发布时间】:2017-01-04 14:48:28
【问题描述】:

我的 resful wcf 服务中有这种方法: 服务合约-

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "CreateTask?t={token}&title={title}&aun={assigneeUsername}&inst={instructions}&tnum={taskNumber}&pr={priority}&ud={userData}")]
Stream CreateTask(string token, string title, string assigneeUsername, string instructions, string taskNumber,
                        string priority, string userData);

服务类:

public Stream CreateTask(string token, string title, string assigneeUsername, string instructions, string taskNumber,
                        string priority, string userData)
{...}

有些参数可能是很长的字符串(~5000),我不希望它们成为查询字符串的一部分,可能会将其中一些作为 FormUrlEncodedContent 发送。

如何将一些参数作为 URL 的一部分发送,而将其他参数作为内容 / 在正文中发送? 我的运营合同可以看起来像这样吗?:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "CreateTask?t={token}")]
Stream CreateTask(string token, string title, string assigneeUsername, string instructions, string taskNumber,
                        string priority, string userData);

我的客户端代码应该是什么样子的?

【问题讨论】:

    标签: c# post wcf-rest


    【解决方案1】:

    只需要在客户端将json格式的值作为HttpContent发送:

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost/MyService/Tasks.svc/");
    
    var url = string.Format("CreateTask?t={0}&ud={1}", token, userData);
    
    var myObject = (dynamic)new JObject();
    myObject.title = title;
    myObject.assigneeUsername = assigneeUsername;
    myObject.instructions = instructions;
    myObject.taskNumber = taskNumber;
    myObject.priority = priority;
    
    HttpResponseMessage response = client.PostAsync(url, new StringContent(myObject.ToString(), Encoding.UTF8, "application/json")).Result;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多