2012-12-16 82 views
1

當我使用POST請求在C#WebApi下面調用時。當我在方法中有一個參數時它工作正常。假設我想包含另一個參數public HttpResponseMessage Post(Member member, bool IsAdmin)那麼data: { id: 2012, firstName: 'FirstNameValue', lastName: 'LastNameValue' }的值是多少?有多個參數的Json Post請求

C#

public HttpResponseMessage Post(Member member) 
    { 
     try 
     { 
      var id = BusinessModule.PostMember(member); 
      member.Id = id; 
      var response = Request.CreateResponse<Member>(HttpStatusCode.Created, member); 
      response.Headers.Location = new Uri(VirtualPathUtility.AppendTrailingSlash(Request.RequestUri.ToString()) + member.Username); 
      return response; 
     } 
     catch (MemberException e) 
     { 
      var response = new HttpResponseMessage(HttpStatusCode.Conflict); 
      response.Content = new StringContent(e.Message); 
      throw new HttpResponseException(response); 
     } 
    } 

jQuery的

function postMember() { 
      $.ajax({ 
       url: baseAddress, 
       type: "POST", 
       // Firefox reuires the dataType otherwise the "data" argument of the done callback 
       // is just a string and not a JSON 
       dataType: 'jsonp', 
       accept: "application/json", 
       data: { id: 2012, firstName: 'FirstNameValue', lastName: 'LastNameValue' }, 
      }) 
      .done(function (data) { 
       $("#membersList").append('<li data-member=\'' + JSON.stringify(data) + '\'>' + data.firstName + ' ' + data.lastName + '</i>'); 
      }) 
      .fail(function (e) { 
       alert(e.statusText); 
      }) 
      .always(function() { }); 
     } 
+0

不清楚是什麼,你甚至問 – charlietfl

+0

** IsAdmin * *這只是一個例子嗎?如果它不確定你已經閱讀了大規模任務攻擊http://odetocode.com/blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-淨mvc.aspx。也許你可以通過他們的安全環境來確定是否有人是管理員,例如索賠,角色等 –

回答

0

看來網絡API不處理多個發佈的內容的值。

請參閱here解釋和可能的解決方法。 我會將新參數放在查詢字符串中,並且在API方法中將從QueryString中讀取變量。

所以,在jQuery的你將有下一行:

url: baseAddress+"?IsAdmin=true", 

而且在C#是:

bool IsAdmin = Convert.ToBoolean(queryItems["IsAdmin"]);