Po tym, jak przez chwilę biłem się w to i próbowałem wielu różnych rzeczy, skończyło mi się umieszczanie punktów przerwania na serwerze API i znajdowanie par kluczowych wartości wypchanych w żądaniu. Po tym, jak dowiedziałem się, gdzie się znajdują, dostęp do nich był łatwy. Jednak znalazłem tylko tę metodę pracy z WebClient.UploadString. Jednak działa wystarczająco łatwo i pozwala załadować tak wiele parametrów, jak chcesz i bardzo łatwo uzyskać do nich dostęp po stronie serwera. Zwróć uwagę, że kieruję reklamy na .net 4.5.
CLIENT SIDE
// 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;
}
Aby uzyskać więcej informacji na temat sposobu obsługi multi-Request.Form wartość par klucz/wartość, patrz:
http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.110).aspx
a jeśli chcesz to zrobić w metodzie pomocnika, a nie całkowicie zrozumieć 'składni await', można użyć' Request.Content.ReadAsAsync() .Result [ "zm1"] ' (patrz [pełna odpowiedź] (http://stackoverflow.com/a/19052895/1037948)) –
drzaus