Passing several query parameters to a GET endpoint in .netcore web api - asp.net-web-api

I have an application where there will be several parameters passed to my endpoint for searching, these parameters are not defined because they are dynamically generated so i cannot map it to a specific model. What would be the best way to map any query parameters into my GET endpoint?
[HttpGet]
public CustomResponse GetResults({something here that will map the parameters?})
{
//perhaps a dictionary? a collection of some sort?
}
Then I need to get all those keys and values and search the database for anything containing that and as i said it could be anything.
So I could pass something like?
/api/Merchandise/GetResults?sku=30021&cupsize=medium&color=red&location=south& {and all the dynamic fields which could be anything}

HttpRequest object has Query property that is an IQueryCollection and holds all passed query parameters.
In other words, in your action method you may do:
[HttpGet]
public CustomResponse GetResults()
{
var queryParams = HttpContext.Request.Query;
// directly get by name
var value1 = queryParams["parameter_name"];
// or queryParams.TryGetValue()
foreach (var parameter in queryParams)
{
string name = parameter.Key;
object value = parameter.Value;
}
}

You could map it to JObject, which is like a Dictionary.
Don't forget:
using Newtonsoft.Json;

Related

Url changes if i don't pass api parameters

I have a common api for search opertaions as well as get operations if the i don't pass the search parameters the URL changes which i don't want.
for eg:
if search parameter is passed:
localhost:8080/api/search?name=harmeet
if no search parameter is passed:
localhost:8080/api/search
what i want is the url should not change whether i pass the parameter or not
for example if i don't pass parameter the url should be:
localhost:8080/api/search?name=''
The code has been written using spring boot
What URL gets called is depended on the client-side and not on the server-side. If you always want a parameter value to be something or "" when it is not passed by the client-side, you can define your controller method as:
#GetMapping("/api/search")
public Object getName(#Requestparam(value="name",required=false,defaultValue="")String name){
// your logic here
// value of 'name' variable will "" if nothing is passed
}
Just set the required field as false and use the defaultValue field to set whatever default value you want to set if the parameter is not provided in the URL call.
As per i understand you want to create API which handle two API calls.
Such as,
http://localhost:8080/search
http://localhost:8080/search?name=hermeet
I supposed you already create API in backend... Right!!!
So, There is not any issue on your logic but parameter which you defined in your method is by default required.
Which don't allow you to pass null or empty value.
You just need to allow your parameter for work with both the cases.
As following ways,
Optional<'Parameter_Type'> parameter_name
#RequestParam(value = "parameter_name", required = false) String variable
Example :
#GetMapping("/search")
public List<Entity> getSearchResult(#RequestParam(value = "parameter_name", required = false) String variable) {
if(variable!=null) {
// Get Data based on condition.
} else {
// Get All Data
}
}
#GetMapping("/search")
public List<Entity> getSearchResult(#RequestParam("parameter_name") Optinal<String> variable) {
if(variable.isPresent()) {
// Get Data based on condition.
} else {
// Get All Data
}
}

SpringBoot named query: IN-clause not working for multiple values

"In clause" not working on passing multiple values
Repository code
#Query( "select myObject from MyObject myObject where myObject.anyColumn in :values" )
public List<MyObject> findPriDestByCntryAbbr(#Param("values") List<String> values);
Calling from service
List<String> values = Arrays.asList(valuesString.split(","));
List<MyObject> result = myObjectRepository.findByAnyColumns(values);
When i am passing single value it is retrieving correct information from table, But on passing multiple values in List "values" giving empty result
Ideally it should work. You should check the values variable.
The other way you can try is- without writing query.
As per the doc we can create MyObjectRepository interface by extending Repository interface and then have a method to fetch all MyObjects. It goes like:
public interface MyObjectRepository extends Repository<MyObject,**Long**> {
List<MyObject> findBy**AnyColumn**In(Collection<String> values);
}
"AnyColumn" is your column name and second parameter for Repository interface is as per your requirement.

How do I post more than one parameter using spring #requestparam/#requestbody annotation in json format

I want to upload an item object with it's image is it possible that i pass a complete object of my Item along with it's image from my Controller if yes then how may i Do it? and I need a Json Pattern also which will be coming from client side.
What would be the Json pattern for my following Item Object.
Class Item{
String ItemID;
String ItemName;
String CategoryID;
List<Image> imagesList;
}
Class Image{
String imageId;
String imageTitle;
byte[] image;
}
and one more thing. Please tell me how can I pass two parameters in my Controller. e.g. if I want to pass Item object in the Request Body along with an extra parameter say String UserID. HOw may I write the following code.
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public void add(#RequestBody Item myItem, String UserID)
{ ...... }
and please tell me what if I pass in the Request in Json format. What will be it looks like?
{ "Item" : { "ItemID": "1", ......}, "UserID" : "hello"}
will it be like this or what? because i tried it i'm getting the Object and string as Null. I also tried it with #RequestParam but same got NULL while debugging.
Currently i'm dealing with this by this.
Class ItemUserPost{
Item item;
String UserID;
}
I'm storing this object in MongoDB. Will be my whole collection of Item will stored along with the images? or i have to use a MultiPart and GridFS API for this. Kindly please refer if related question already posted.
Please Help Urgent.
Thanks in Advance.
The Request Body it's just ONE body. You cannot pass multiple objects or parameters in the same body.
There is 2 turnovers for this:
If you're using REST, you can put the UserID on #RequestMapping(value = "{userId}") and get it from the URL. Or, you can simply put the UserId as query parameter on your url.
Keep using your ItemUserPost object.
--
And for the second question:
Yes, It will store your collection with the images.

How to use the array of values in the WHERE clause of my query

I am using asp.net mvc3. I want to pass an array from view to the controller using parameterMap as shown below. In my view:
parameterMap:
function (data, options) {
if (options === "read") {
sessionStorage.setItem("value","array");
val = sessionStorage.getItem("value"); // contains array
return { model: JSON.stringify(val) }; //passing array to controller
}
}
In controller:
public ActionResult SearchDetails( string model)
{
var query = (from ......).where();//want to compare array values in controller
}
but I am not able to retrieve those values in the controller. How can I retrieve these array of values in my controller without using looping statements?
My array contains only integer values (ids), while debugging the when I put cursor at the parameter of action method the values are coming in ""[{\"id\":1},{\"id\":2}]"" format. How can I use this array of values in my WHERE clause of my query?
if you are bound and determined to stick with the string input, I would think a call to Split would work. However, it would be much easier if you changed from bringing it in as a string to just bringing in the model. Have you tried something like:
public ActionResult SearchDetails( model model)
{
var query = (from ......).where();//want to compare array values in controller
}
are you trying to do something equivalent to a SQL IN? If that is the case then use .Contains in your query. For example:
public ActionResult SearchDetails(model model)
{
var query = from d in context.data
where model.Contains(d.id)
select d;
}

Is it possible to pass object as route value in mvc 3?

I'm trying to refactor some of my code and i'm wondering if it is possible something like this:
This is part of my cshtml:
<a href="#Url.Action("Vote", "Ideas", new { id = item.Idea.Id, pageMetadata = Model.PageMetadata, numberOfVotes = 2 })">
This is invoking action:
public ActionResult Vote(string id,PageMetadata pageMetadata, int numberOfVotes = 1)
And PageMetadata is my class.
When im debbuging in cshtml site pageMetadata is correct,but when action is invoking pageMetadata it's becoming to null. Do I some stupid mistake or all idea is wrong?
Thanks for any help.
Query strings are like dictionary : {key, value} pairs. Therefore you cannot pass your class objects in query strings.
But, what you can do, is to pass this the id for your model object and then use that id to load your object on server.
Right now, you are working on a wrong notion ! :-)
One other option is to serialize / deserialize the object for example:
<a href="#Url.Action("Vote", "Ideas", new { id = item.Idea.Id, pageMetadata = JsonConvert.SerializeObject(Model.PageMetadata), numberOfVotes = 2 })">
in the controller:
public ActionResult Vote(string id,string pageMetadata, int numberOfVotes = 1)
var pageMetadataObj = JsonConvert.DeserializeObject<PageMetadata>(pageMetadata)
Note: this will expose your object properties to the browser and could add significant size to the webpage depending on the number and type of objects.
You can use Html.ActionLink method :
https://www.aspsnippets.com/Articles/Pass-Send-Model-from-View-to-Controller-using-ActionLink-in-ASPNet-MVC.aspx

Resources