I submit data via a xhr request which contains POST data along with some URL params where the POST data is a JSON string.
Here is a sample controller and a sample url
public ActionResult Update(string collection)
{
/* method body */
}
somepath/SomeController/Update?_id=r43r34r34r&collection=astring
If the POST data now looks like
{
collection: 'SomeString'
}
MVC overwrite the param from the URL so that within the controller the collection string has 'SomeString' as value instead of 'astring'. Is there a way to prevent this behavior?
The only way around this, beyond using a custom model binder to prioritise the URI, would be to either:
Change the name of the parameter in the query string and in the action method parameters to something that isn't in the POST request body.
Pick up directly from the query string in the controller:
var aCollection = Request.QueryString["collection"].ToString();
If you change your method signature to Update(string[] collection) you might get (i'm not sure) all the values.
Related
I have a method as described below which get user as parameter.
To send the user parameter values, I am using postman request/response tool.
My question is, if the request already have user parameter in body request (see at the postman print screen ) why do I need to directly specify [FromBody] in action controller? When this attribute removed, parameter send with null values.
Thanks
[HttpPost("register")]
public IActionResult Register([FromBody]User user)
{
//.. code here
}
public class User
{
public string Name { get; set; }
public string Password { get; set; }
}
The [FromBody] directive tells the Register action to look for the User parameter in the Body of the request, rather than somewhere else, like from the URL. So, removing that confuses your method, and that's why you see null values as it's not sure where to look for the User parameters.
See: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api for more information/learning.
For Model Binding in ASP.NET Core, MVC and Web APi uses the same model binding pattern.
There are default model bindings like Form Values, Route values and Query Strings. If these bindings fails, it will not throw an error, and return null.
If you do not want to add [FromBody], you could try Form Values binding and send request from Postman like below:
[FromBody] will override default data source and specify the model binder's data source from the request body.
You could refer Model Binding in ASP.NET Core for detail information
the attribute [FromBody] ensures the API reads the JSON payload in the postman body. For more info, read
https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
I just wanted to know if there is a way I could prevent ASP.net Web API controller from converting json string from the requests body into an object, I just want it as is.
for example:
public HttpResponseMessage PostJson(int id, [FromBody] string jsonString)
{
// code processing here
}
The above code accepts two parameters for id and a json string which should be posted along with the body of the request. When the method accepts the post request it will mapped the value of the id, but not with the jsonString because as with its default behavior it will convert it into an object.
Is there a way to ignore it? Thanks in advance.
I have a Web API action that looks like the following:
[HttpGet]
[Route("api/query/hello/{query}")]
public HttpResponseMessage Hello([FromUri]Query query)
{
return null;
}
where the Query class has a public string property named QueryText. When I hit the following URL, I get a 404 error:
/api/query/hello?QueryText=bacon
This worked before I started using Attribute Routing. If I have no parameters or primitive type parameters, I can get Attribute Routing to work. But with a complex parameter, I get 404s. How does Attribute Routing work with complex action parameters? Is it compatible with the FromUri attribute?
The solution here was that the {query} token in the Route definition was superfluous. Removing it, as follows, fixed the issue:
[Route("api/query/hello")]
The [FromUri] attribute will be needed because you're reading from the URL. Your route should look something like:
public HttpResponseMessage Hello([FromUri]Query query)
{
//Implement whatever
return null;
}
/api/{Controller Name}/hello?QueryText=bacon
Should then work correctly.
The model binder will take whatever query parameters you provided then try to bind whatever is inside that Query object. I'd worry about the Route Attribute after you've got it working first.
I'm new to ASP.NET MVC and it's my first time working with an API.
I'm trying to do a PUT, given an object. However, after starting the application and looking at the available API, it shows my PUT URL as the following, without any option for arguments.
/api/File
Shouldn't it be something like /api/File/{}?
Controller
[HttpPut]
public void PutFile (FileData file)
{
...
}
If I'm doing this completely wrong, please let me know!
That URL is correct since the object you are sending should be passed in the body of the request with the correct content type.... probably multipart/form-data if you are uploading a file. If FileData is not a file and just a complex object then you could use application/x-www-form-urlencoded for forms or application/json for AJAX.
tforester answer is correct, but just to add. You need to use the FromBodyAttribute to tell webapi that the non primitive object (e.g. FileData) is expected and it's in the body of the incoming request. e.g.
[HttpPut]
public void PutFile ([FromBody]FileData file)
{
...
}
I am testing a push notification on a calendar application. When I create an event on calendar application, my website gets a HttpPost request with a JSON string. I wrote code like this but I couldn't receive the JSON string in my action method.
[HttpPost]
public ActionResult Push(String jsonReq)
{
Console.write(jsonReq);
return View();
}
When I create model in the same structure as JSON, then I can receive the request. it seems to be tightly coupled to JSON structure ? I am using in ASP.Net MVC 4.
[HttpPost]
public ActionResult Push(JSONModel jsonModel)
{
return View();
}
ASP.NET MVC model binding works the following way - it parses the request, tries to find a name-to-name corresponding between its parameters and Action paramaters, and if found instantiates latter. You are not sending parameter with name jsonReq, so you cannot receive something in your action method.
If you really want to work with plan json string without letting ASP.NET MVC parse it for your, you have two options:
Access it via HttpContext.Request inside the action
Write custom model binder that will map the request body to the jsonReq parameter
The request would not have a value named jsonReq so would not know to map the json to that action parameter.
Where as your JSONModel will have property names that match the JSON named values coming into the request thus the object us populated.