未收到REST服务参数 - 更改控制器以匹配调用例程

时间:2017-06-13 14:52:15

标签: c# wcf-data-services

我有一个无法更改的调用例程(与建议的FromBody not binding string parameterASP.NET web api cannot get application/x-www-form-urlencoded HTTP POST不同),需要调整控制器才能匹配。调试控制器时,即使数据正在线路上传递,变量msg也是null。目标是允许将XML文件发送到控制器。

控制器需要更改哪些内容才能收到数据?

API控制器

    public class ApiInterchangeController : ApiBaseController
    {
       [HttpPost]
       public HttpResponseMessage ServiceCallAction([FromBody]string msg)
       {
           if (string.IsNullOrEmpty(msg))
           {
               var httpError = new HttpError("No Data Sent");
               return Request.CreateResponse(HttpStatusCode.BadRequest, httpError);
           }
       }
    }

调用例程

string filePath = Server.MapPath("Temp") + "\\";
string fileName = "SampleData2.txt";
string xmlMsg = System.IO.File.ReadAllText(filePath + fileName);

// sample data for point of reference
// xmlMsg = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<DATA ID=\"25379\">\r\n</DATA>"

string URL = "http://localhost:53417/API/ApiInterchange/ServiceCallAction";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] byteData = System.Text.Encoding.UTF8.GetBytes("msg=" + Uri.EscapeDataString(xmlMsg));
request.ContentLength = byteData.Length;

using (var postStream = request.GetRequestStream())
{
   postStream.Write(byteData, 0, byteData.Length);
   postStream.Close();
}

var response = request.GetResponse() as HttpWebResponse;

0 个答案:

没有答案