2012-10-29 37 views
13

Tôi đang thực hiện yêu cầu làm một phương pháp đăng bài asp.net webapi, và tôi không thể nhận được yêu cầu biến.Cách lấy Giá trị Bài đăng của Json với asp.net webapi

Yêu cầu

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"); 

    } 

tôi không thể có được nội dung var1 trong cả hai cách ... (trừ khi tôi tạo ra một lớp cho rằng)

Tôi nên làm như thế nào?

Trả lời

22

cách đầu tiên:

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

Lưu ý rằng value.Property thực sự trả về một trường hợp JToken như vậy để có được giá trị của nó bạn cần phải gọi value.Property.Value.

cách thứ hai:

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

Cả hai công việc trên sử dụng Fiddler. Nếu tùy chọn đầu tiên không hoạt động đối với bạn, hãy thử đặt loại nội dung là application/json để đảm bảo rằng JsonMediaTypeFormatter được sử dụng để deserialize nội dung.

+1

và nếu bạn muốn làm điều này trong một phương pháp helper, và không hoàn toàn hiểu được những 'cú pháp await', bạn có thể sử dụng 'Request.Content.ReadAsAsync () .Result [ "var1"]' (xem [câu trả lời đầy đủ] (http://stackoverflow.com/a/19052895/1037948)) – drzaus

-5

hãy thử sử dụng cách sau

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

Sau khi đập đầu vào một lúc và thử nhiều thứ khác nhau, tôi đã đặt một số điểm ngắt trên máy chủ API và tìm thấy các cặp giá trị quan trọng được yêu cầu. Sau khi tôi biết chúng ở đâu, thật dễ dàng để truy cập chúng. Tuy nhiên, tôi chỉ tìm thấy phương pháp này để làm việc với WebClient.UploadString. Tuy nhiên, nó hoạt động đủ dễ dàng và cho phép bạn tải lên bao nhiêu thông số tùy thích và rất dễ dàng truy cập vào phía máy chủ. Lưu ý rằng tôi đang nhắm mục tiêu .net 4.5.

KHÁCH HÀNG PHỤ

// 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; 
} 

Server Side

// 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; 
} 

Để biết thêm về cách xử lý đa giá trị cặp Request.Form Key/Value, xem:

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

0

Hãy thử điều này.

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

    // ... 
} 
Các vấn đề liên quan