Calling a web api method with custom object - asp.net-mvc

Usually I send my post request with a custom parameter and a custom return and object using
HttpClientExtension.PostAsJsonAsync<T>
This allows my to call a post method with a custom object.
Now, I want to be able to send my custom object as a parameter and return value to a GET Method.
Lets say my method signature is
[HttpGet]
public MyMethodResponse MyMethod(MyMethodRequest request)
How can I send a request when I have an instance of MyMethodRequest ?
Thanks.

You need to encode MyMethodRequest onto the query string. You can either encode it as separate query string parameters or as a single one. You have handle the encoding yourself on the client side, remembering to URI-encode the parameters. Decoding is done using a custom ModelBinder or TypeConverter respectively. This article shows examples of binding a complex object on the query string.

Related

MVC POST default binding

I have an MVC WebApi app. I'm trying to do something basic - pass a string via JSON in the body. My client submits a small number of key/value parameters, and when the MVC router gets them, it begins to interpret the content of the strings.
An example JSON body is
{ "myKey":"red,yellow,brown,orange","foo":"bar" }
My MVC controller method is
public Dictionary<string, string> PostMyAction([FromBody] str1, [FromBody] str2) { }
I would expect str1 == "red,yellow,brown,orange" but instead I get "Can't bind multiple parameters ('str1') to the request's content."
Why is it parsing the first string as a list of parameters?
Shouldn't your Controller method be an ActionResult?
You do can receive more than one parameter on your actions, but for a clear code, I recomend use one ViewModel that contains properties that will represent your View, and Binded on submit.

How to bind JSON to model within a method?

I understand that MVC4 can automatically bind json to type models.
For example, take an HTMLItem model.
In part of a method I retrieve the HTMLItem model data in json format from an external site using HttpRequest and StreamReader. I grab this as a string and then want to pass it into another method that takes HTMLItem as a parameter.
How do I ensure that the receiving method handles this as the type I require (HTMLItem)? It currently doesn't recognise it as such.
I tried assigning the string to the model in the originating method, but the IDE gives me the red squiggly for assigning a string to another type.
I don't want to have to go through the json string and assign each field manually if possible.
Any help, as always, much appreciated. Thanks.
You could deserialize the JSON to your model like:
using System.Web.Script.Serialization;
...
JavaScriptSerializer serializer = new JavaScriptSerializer();
YourModelType model = serializer.Deserialize<YourModelType>(yourJSON);

Passing a List<string> to an MVC Web API method using the browser bar

I have an MVC Web API Get method that accepts a List<string> as a parameter. I'm trying to access this method using simply the browser bar. How is this done? Using ../APIName?parameter1=value1&parameter2=value2&... passes a single parameter between two ampersands as opposed to a list.
Make sure your parameter of your action method is marked as [FromUri]. By default the value is expected to be passed from the body of the request since it is a complex type.
public List<string> Get([FromUri] List<string> parameter)
{...}
The query string parameter should be of this format .../APIName?parameter[]=value1&parameter[]=value2&....
Hope this helps.

Silverlight and MVC: post object to controller method

I have an MVC project in which a controller action returns some JSON data (i.e. via /Home/GetData URL). This action also takes a custom object as a param.
This signature for the action is JsonResult GetData (MyCustomObject o)
I also have a client Silverlight project in which I'm constructing MyCustomObject and trying to call this URL (/Home/GetData/) via HttpWebRequest. However, I'm having trouble figuring out how to post in my object in this call. Do I need to serialize it to Json in order to pass it in?
Thanks so much!
MVC can accept and bind the submitted data to your MyCustomObject object, regardless of whether it is submitted as JSON, XML, a query string, a standard form POST, etc.
MVC does not require the object to be submitted in a particular fashion. That is up to you as the designer to determine what works best under the particular circumstances, given all of your requirements.
When submitted, MVC will use the ValueProvider suitable to the form of the data submitted, and the DefaultModelBinder will attempt to use the values in the ValueProvider to bind to your model.
Thanks for your help! Since the web app handles this with a getJSON call, I ended posting the object as a query string param i.e. I'm making a web request to http://../controller/action/view.aspx?custObject.property1=<value>&custObject.property2=<value> etc

Request.Form not populated when using the HTTP PUT method (ASP.NET MVC)

I'm attempting to process the body of an HTTP PUT request, but it seems that the MVC engine (or perhaps the ASP.NET stack underpinning it) isn't automatically parsing & populating the request's Form collection with the body data.
This does work as expected when doing a POST.
Note that the request's InputStream property does contain the expected data, and obviously I can build my own key/value collection using that, however I would have expected PUT to work the same way as a POST.
Am I missing something here?
Example action method:
[AcceptVerbs(HttpVerbs.Put)]
public ActionResult Purchase(int id, FormCollection data)
{
// Do stuff with data, except the collection is empty (as is Request.Form)
}
Quote from the doc:
The Form collection retrieves the
values of form elements posted to the
HTTP request body, with a form using
the POST method.
So instead of using Request.Form I would recommend you writing a custom model class that will hold the request data and pass it as action parameter. The default model binder will automatically populate the properties from the key/values passed in the request stream:
[AcceptVerbs(HttpVerbs.Put)]
public ActionResult Purchase(MyCustomModel model)
{
// Do stuff with the model
}
Asp.net does not support PUT out of the box for custom requests. If you are using not the built in capabilities to generate the PUT url try adding X-HTTP-Method-Override with value of PUT in headers, form, or query string.

Resources