2016-08-16 3 views
2

バックエンド、ASP.netコアAPI:Angular 2からASP.net CoreへのPOST要求が機能しません。サーバー側でヌル値

[Produces("application/json")] 
    [Route("api/[controller]")] 
    public class StoriesController : Controller 
    { 
     public static List<Story> STORIES = new List<Story> 
      { 
       new Story 
       { 
        content = "Some really interesting story about dog", 
        timeOfAdding = new DateTime(2016, 8, 26), 
        numberOfViews = 11 
       }, 
       new Story 
       { 
        content = "Even cooler story about clown", 
        timeOfAdding = new DateTime(2016, 9, 26), 
        numberOfViews = 11 
       }, 
       new Story 
       { 
        content = "And some not cool story", 
        timeOfAdding = new DateTime(2016, 10, 26), 
        numberOfViews = 11 
       } 
      }; 

     // POST api/values 
     [HttpPost] 
     public void Post([FromBody]string value) 
     { 
      Story story = new Story 
      { 
       content = value, 
       timeOfAdding = DateTime.Now, 
       numberOfViews = 0 
      }; 
      STORIES.Add(story); 
     } 
    } 

活字体の機能:(Firefoxのコンソールで見られる)が送信

add(content: string): Observable<Story> { 
     let body = JSON.stringify({ "value": content }); 
     //let body = { "value": content }; 
     let headers = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: headers}); 

     return this.http.post(this.heroesUrl, body, options) 
      .map(this.extractData) 
      .catch(this.handleError); 
    } 

パラメータ:

enter image description here

Visual Studio 2015デバッガのvalue = null

どういうところが間違っていますか?私はインターネットで見つけたすべてを試しました。つまり、ヘッダの追加/削除、JSON.stringifyの削除、[FromBody]属性の追加/削除です。結果は毎回同じです。

答えて

6

あなたは(スクリーンショットが示すように)JSONとしてあなたの価値を渡しているので、あなたは正しく結合モデルを使用して、代わりに文字列入力の適切なクラスを使用する必要があります。

public class StoryAddRequest 
{ 
    public string Value { get; set; } 
} 

あなたはそれを使用することができますお使いのコントローラで:documentationから

// POST api/values 
[HttpPost] 
public void Post([FromBody] StoryAddRequest request) 
{ 
    if (request != null) 
    { 
     Story story = new Story 
     { 
      content = request.Value, 
      timeOfAdding = DateTime.Now, 
      numberOfViews = 0 
     }; 
     STORIES.Add(story); 
    } 
} 

リクエストデータをfの様々な来ることができ

JSON、XMLなどを含むormats。 [FromBody]属性を使用して、要求本体のデータにパラメータをバインドすることを示す場合、MVCは構成済みのフォーマッタのセットを使用して、そのコンテンツタイプに基づいて要求データを処理します。 MVCにはデフォルトでJSONデータを処理するための JsonInputFormatterクラスが含まれていますが、XMLやその他のカスタムフォーマットを処理するためのフォーマッタを追加することができます。

+0

1つの文字列パラメータを渡したい場合は、別のクラスを作成する必要がありますか? AFAIK文字列はクラスそのものなので、なぜ文字列を渡すことができないのですか? – Piotrek

+0

文字列だけでなく、そこにJSONを渡しています。 – rinukkusu

+0

したがって、内部JSONデシリアライザは '{" value ":" yyyyy "}'を 'String'クラスに逆シリアル化できません。 – rinukkusu

関連する問題