2012-10-29 21 views
13

我正在做一個請求做一個asp.net webapi Post方法,並且我不能夠獲取請求變量。如何使用asp.net webapi獲得Json Post值

請求

jQuery.ajax({ url: sURL, type: 'POST', data: {var1:"mytext"}, async: false, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=UTF-8' }) 
    .done(function (data) { 
     ... 
    }); 

WEB API FNX

[AcceptVerbs("POST")] 
    [ActionName("myActionName")] 
    public void DoSomeStuff([FromBody]dynamic value) 
    { 
     //first way 
     var x = value.var1; 

     //Second way 
     var y = Request("var1"); 

    } 

我不能獲得這兩種方式的VAR1的內容...(除非我創建一個類)

我應該怎麼做?

回答

22

第一種方式:

public void Post([FromBody]dynamic value) 
    { 
     var x = value.var1.Value; // JToken 
    } 

注意value.Property的實際返回JToken實例,以便讓您需要調用value.Property.Value值。

方式二:

public async Task Post() 
    {   
     dynamic obj = await Request.Content.ReadAsAsync<JObject>(); 
     var y = obj.var1; 
    } 

無論使用招上面的工作。如果第一個選項不適合您,請嘗試將內容類型設置爲application/json,以確保JsonMediaTypeFormatter用於反序列化內容。

+1

,如果你想這樣做的一個輔助方法,不完全理解了'await'語法,你可以用'Request.Content.ReadAsAsync ()。結果[「VAR1」]' (請參閱[完整答案](http://stackoverflow.com/a/19052895/1037948)) – drzaus

-5

嘗試使用以下方式

[AcceptVerbs("POST")] 
[ActionName("myActionName")] 
public static void DoSomeStuff(var value) 
{ 
    //first way 
    var x = value; 
} 
6

在我敲了一下腦後,嘗試了很多不同的事情後,我終於在API服務器上放了一些斷點,並發現請求中填充了關鍵值對。在我知道他們在哪裏之後,很容易找到他們。但是,我只發現這種方法與WebClient.UploadString一起工作。但是,它確實很容易工作,並允許您隨意裝載儘可能多的參數,並且可以非常方便地訪問它們的服務器端。請注意,我的目標是.net 4.5。

客戶端

// Client request to POST the parameters and capture the response 
public string webClientPostQuery(string user, string pass, string controller) 
{ 
    string response = ""; 

    string parameters = "u=" + user + "&p=" + pass; // Add all parameters here. 
    // POST parameters could also easily be passed as a string through the method. 

    Uri uri = new Uri("http://localhost:50000/api/" + controller); 
    // This was written to work for many authorized controllers. 

    using (WebClient wc = new WebClient()) 
    { 
     try 
     { 
      wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; 
      response = wc.UploadString(uri, login); 
     } 
     catch (WebException myexp) 
     { 
      // Do something with this exception. 
      // I wrote a specific error handler that runs on the response elsewhere so, 
      // I just swallow it, not best practice, but I didn't think of a better way 
     } 
    } 

    return response; 
} 

服務器端

// In the Controller method which handles the POST request, call this helper: 
string someKeyValue = getFormKeyValue("someKey"); 
// This value can now be used anywhere in the Controller. 
// Do note that it could be blank or whitespace. 

// This method just gets the first value that matches the key. 
// Most key's you are sending only have one value. This checks that assumption. 
// More logic could be added to deal with multiple values easily enough. 
public string getFormKeyValue(string key) 
{ 
    string[] values; 
    string value = ""; 
    try 
    { 
     values = HttpContext.Current.Request.Form.GetValues(key); 
     if (values.Length >= 1) 
      value = values[0]; 
    } 
    catch (Exception exp) { /* do something with this */ } 

    return value; 
} 

有關如何處理多值的Request.Form鍵/值對的詳細信息,請參閱:

http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.110).aspx

0

試試這個。

public string Post(FormDataCollection form) { 
    string par1 = form.Get("par1"); 

    // ... 
}