コンテンツタイプがXMLに設定されているため、XMLとしてデータを渡す必要があります。これは、データを<string>
要素にラップすることを意味します。
RestSharp(http://restsharp.org/)を使用して.NetからWebAPI呼び出しを行うことをお勧めします。
var client = new RestClient("http://localhost:1748/");
var request = new RestRequest("api/SomeAPI", Method.POST);
request.AddBody("Test");
var response = client.Execute(request);
更新
私は、サンプルプロジェクトを作成しているし、それは絶対に正常に動作します:
サーバー側:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class HomeController : ApiController
{
[Route("api/TestAPI")]
[HttpPost]
public IHttpActionResult Post([FromBody]String test)
{
return Ok(string.Format("You passed {0}.", test));
}
}
}
クライアント側:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/TestAPI");
req.Method = "post"; ;
var aaa = Encoding.Default.GetBytes("\"Test\"");
req.ContentType = "application/json";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
}
IISでWeb APIサービスをインストールし、コンソールアプリケーションを実行した後に、印刷します。
"You passed Test."
を応答を囲む引用符に注意してください。 あなたはXMLを使用したい場合、あなたはあなたが送信されているコンテンツの種類とデータを変更する必要があります:あなたが得る
var aaa = Encoding.Default.GetBytes("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Test</string>");
応答は、デバッガ内の両方のサンプルがあります
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">You passed Test.</string>
ですテストパラメータに渡された正しい値。私はそれを閉じる()を呼び出すことができるように
は以前、私は)(GetRequestStreamを分割しました。 –
@RobLang:私はすでにそれを試みましたが、まだヌルになっています。 – Arrrr
HTTPアナライザーのようなスニファを使用してリクエストを確認しようとしましたが、リクエストに問題があるようです。あなたは、サンプルリクエストを送信するために、クロム事前のレストクライアントを使用することができます。 – Vladimir