私はAsp.Net Core
を使って開発した単純なWeb APIを持っていて、HttpClientを使ってキーと値のペアを投稿しようとしています。私は2つのアプローチを試しました。asp.netコアのweb apiに辞書を投稿する
第一のアプローチ
[Route("api/[controller]/[action]")]
public class TransformationController : Controller
{
private IServiceResolver _serviceResolver;
public TransformationController(IServiceResolver serviceResolver)
{
_serviceResolver = serviceResolver;
}
[HttpPost]
[ActionName("Post1")]
public void Post1([FromBody]Dictionary<string, string> data)
{
// do something
}
}
、その後、私は
[Fact]
public void TestPost1()
{
var content = new Dictionary<string, string>();
content.Add("firstname", "foo");
var httpContent = new FormUrlEncodedContent(content);
var client = new HttpClient();
var result = client.PostAsync("http://localhost:17232/api/Transformation/Post1", httpContent).GetAwaiter().GetResult();
}
以下のようにそれを掲示していますが、私はUnsupported Media Type
エラー
{のStatusCode取得しています:415、のreasonPhraseを 'サポートされないメディアタイプ '、バージョン: 1.1、Conte NT:System.Net.Http.StreamContent、ヘッダー:{日:月、2016年8月29日午前19時44分44秒GMTサーバー:ケストレルX-、ソースファイル:???? = UTF-8 B QzpccmVwb3NcY3ItbWV0YXRhc2tlclxzcmNcSW5ib3VuZEludGVncmF0aW9uXFRyYW5zZm9ybWF0aW9ucy5BcGlcYXBpXFRyYW5zZm9ybWF0aW9uXFRyYW5zZm9ybWF0aW9uMQ == = X- ASP.NETのContent-Length:0}}
アプローチ2
IはFormUrlEncodedContent
コンテンツタイプとエンコーディングを指定することができないので、私は、POSTメソッドのシグネチャを変更し、そして今ではJSONを取り込みによって供給パラメータとしての文字列。アイデアは、文字列を辞書に逆シリアル化することです。
[HttpPost]
[ActionName("Post2")]
public void Post2([FromBody]string data)
{
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
// do something here
}
と私はテストをデバッグするとき、私はしかし
[Fact]
public void TestPost2()
{
var httpContent = new StringContent("{ \"firstName\": \"foo\" }", Encoding.UTF8, "application/json");
var client = new HttpClient();
var result = client.PostAsync("http://localhost:17232/api/Transformation/Post2", httpContent).GetAwaiter().GetResult();
}
以下のように文字列を掲示しています。ポスト2メソッドのdata
パラメータがnullです。
両方のアプローチで私がここで何が欠けているのか分かりませんか?私はその作業を、データを投稿するPOSTMANを使用している場合、誰かが
アップデート1
を助けてくださいすることができます。だから私はHttpClientを
レポジトリまたはモデルを使用していますか? – Aravind
私はリポジトリまたはモデルを使用していません。実際にはリポジトリやモデルとは関係ありません。 APIはキーと値のペアを取り、それを使って何かを行います。 – LP13