2016-05-02 19 views
3

したがって、FormDataCollection.ReadAsNameValueCollection()を使用して、複数のパラメータをフィドラーからWeb APIに渡そうとしています。 問題が毎回私のデータを送信している、formDataはnullとして戻ってきます。私はここで何が間違っているのか分かりません。私はformData[FromBody]属性で装飾しようとしました。また、global.asaxクラスにJsonMediaTypeFormatter()を登録しました。Asp.Net Web Apiマルチパラメータパラメータ

ご協力いただければ幸いです。

以下のコードを参照してください。

[HttpPost] 
public HttpResponseMessage PostAccount([FromBody]FormDataCollection formData) 
{ 
    if (formData != null) 
    { 
     var nValueCol = formData.ReadAsNameValueCollection(); 

     var account = new Account() 
     { 
      Email = nValueCol["email"], 
      Password = nValueCol["password"], 
      AgreedToTerms = Convert.ToBoolean(nValueCol["agreesToTerms"]), 
      //LocationAccountCreated = DbGeography.FromText(nValueCol["userLocation"]) 
     }; 

     var userProfile = new UserProfile() 
     { 
      FirstName = nValueCol["firstName"], 
      LastName = nValueCol["lastName"], 
      DateOfBirth = Convert.ToDateTime(nValueCol["dateOfBirth"]) 
     }; 

     var newAcc = _accountService.CreateAccount(account.Email, userProfile.FirstName, userProfile.LastName, 
                userProfile.DateOfBirth, account.Email, account.AgreedToTerms, 
                account.LocationAccountCreated); 
     var response = Request.CreateResponse(HttpStatusCode.Created); 

     return response; 
    } 
    else 
     return Request.CreateResponse(HttpStatusCode.NotAcceptable); 
} 

をサンプル要求:

Fiddler Post Request

+0

リクエストで送信しているContent-Typeはどれですか?リクエストの本文を表示できますか? –

+0

こんにちはフェデリコ、私はフィドラーリクエストのスクリーンショットをアップロードしました。しかし私はapplication/jsonを使いました – user6201138

答えて

4

FormDataCollectionは通常application/x-www-form-urlencodedメディアタイプに関連付けられています。

あなたのスクリーンショットは、あなたがjsonデータを送信しようとしていることを示しています。データの具体的なデータ型がなく、Jsonとして送信する場合は、IDictionary<string,string>を使用してモデルバインダーによって正常にマップされます。

あなたの行動のようなTestControllerが作成された、要求はシオマネキでテストされた、あなたのコードとあなたのシオマネキのスクリーンショットからの情報に基づいて何かのような...

[HttpPost] 
public HttpResponseMessage PostAccount([FromBody]IDictionary<string, string> formData) { 
    if (formData != null) { 
     var nValueCol = formData; 
     //...other code removed for brevity, but can basically stay the same 
     var response = Request.CreateResponse(HttpStatusCode.Created); 
     return response; 
    } else 
     return Request.CreateResponse(HttpStatusCode.NotAcceptable); 
} 

を見ていきます...

POST http://localhost:35979/api/account/create HTTP/1.1 
User-Agent: Fiddler 
Host: localhost:35979 
Content-Type: application/json 
Content-Length: 76 

{"email":"[email protected]", 
"firstname":"myFName", 
"lastName":"myLName"} 

... formDataには、3つのフィールドとそのデータが設定されていました。