Asp.Net Web Api - Change parameter name - asp.net-web-api

In my team we have coding rule that requires that every function's parameter starts with prefix, e.g. *p_someParam*.
With Web Api if we want to request a GET function that takes two parameters, we should add those parameters like "...?p_firstParam=value1&p_secondParam=value2".
Is there some way to use in requests more user-friendly names, like someParam without prefix, that will automatically map to parameters in controller's action? Maybe there is some attribute to rename action parameters? I couldn't find any similar example.
Every clue is appreciated.

I think you looking for URL rewriting, in that you need to map the urls to config or programmatic
http://www.codeproject.com/Articles/2538/URL-Rewriting-with-ASP-NET nice article to follow, its in ASP.Net,

Related

Calling a controller/action through query parameters

Is it possible to call a controller and action directly by using query parameters in Laravel? I see some frameworks allow /index.php?_controller=X&_action=Y, or Yii allows /index.php?r=X/Y. I was wondering if something similar was possible in Laravel/Symfony.
symfony
The query string of a URL is not considered when matching routes. In this example, URLs like /blog?foo=bar and /blog?foo=bar&bar=foo will also match the blog_list route.
https://symfony.com/doc/6.0/routing.html
laravel afaik doesnt support that either
you are obviously free to just forward yourself
e.g. write one router that forwards to other controllers
symfony https://symfony.com/doc/6.1/controller/forwarding.html

Laravel DELETE request as API

When you want to delete an item from the db, I know that you can use /resource/{id} and use the contrller#destroy action.
What is the advantage of passing a parameter in the URL as oppose to send a DELETE request and pass the parameter $id via an Input?
You can certainly do both, but the first method (using the dedicated /resource/{id} URL) is following the RESTFUL design pattern. Here is a very good video on that.
To highlight some important points:
We avoid verbs in URLs, unless they're used for very specific actions. We should try to use nouns instead if it's possible, so a url like /resource/deleteis not advisable.
When someone used to the REST way of communicating with an API uses 'DELETE' on the /resource url, he/she expects to delete ALL resources. If he/she uses it on /resource/{id}, then only that specific item should be removed.
Hope this made sense =)

Passing multiple values as query string is good or bad practice in MVC

In my page I ve to pass multiple values to controller.
My URL looks something like :
http://blah/Search/Page/?type=new&keywords=blahblah&sortType=Date
Is Passing multiple values as query string good practice in MVC ? or We can have slash separated URL, by using introducing custom routing?
NB: Lets consider all the values in my query string, are not secure / sensitive data.
I wouldn't consider it a bad practice, as long as it's not senstive data. It just depends if you want to write a custom route in your global.asax to handle it or not. The custom routes provide a cleaner url forsure. Also, for more savy users if they understand the concept on your site, it's more intuitive.
So consider this:
http://baseballcards/topps/1980 // search for baseball cards made by topps in the 1980s
http://recipes/deserts/pies // search for a desert recipe that are pies
http://code/csharpe/linq // search for csharp code that has linq examples
In these examples we can almost read the url like a sentence, making it more intuitive, giving a user the ability to plug and play. It clearly denotes the query almost like a breadcrumb, indicating exactly what the context will be. I personally like this. But either way is a good approach.
To extend with more parameters:
routes.MapRoute(
"SearchRecipes",
"Search/Recipes/{category}/{type}",
new { controller = "Search", action = "Recipes", category = "all" , type = ""}
);
Some examples:
Search/Recipes/Deserts/Pie
Search/Recipes/Dinner/Beef
Search/Recipes/Lunch/Salads
Select later (query string in route values) in case,
If you are concerned about header length.( By default get parameters are part of headers, and web server accept 1024 byte header length by default in IIS7).
Hide logical implementation of your code.
Url looks good and easier to remember.
Otherwise Both the approaches work equally.
I think passing search parameters in the query string is the way you should go, especially if all your parameters are optional. It also enables you to use normal method="get" forms without hassle.
I don't think "security/personal data" has anything to do with this since the query string is a part of the URL just like the path is.
IMO I think this is absolutely fine. I think it is actually preferable to use querystrings in MVC when the path represents the function and the querystring parameters represent the filters, e.g. as in a search.
However, I wouldn't use querystring parameters for data that represent information about the content retrieved. So I would include the year and month of an article in the path but not the page number if returning more than one page of articles for the year and month.

Combining GET and POST in Sinatra (Ruby)

I am trying to make a RESTful api and have some function which needs credentials. For example say I'm writing a function which finds all nearby places within a certain radius, but only authorised users can use it.
One way to do it is to send it all using GET like so:
http://myapi.heroku.com/getNearbyPlaces?lon=12.343523&lat=56.123533&radius=30&username=john&password=blabla123
but obviously that's the worst possible way to do it.
Is it possible to instead move the username and password fields and embed them as POST variables over SSL, so the URL will only look like so:
https://myapi.heroku.com/getNearbyPlaces?lon=12.343523&lat=56.123533&radius=30
and the credentials will be sent encrypted.
How would I then in Sinatra and Ruby properly get at the GET and POST variables? Is this The Right Way To Do It? If not why not?
If you are really trying to create a restful API instead if some URL endpoints which happen to speak some HTTP dialect, you should stick to GET. It's even again in your path, so you seem to be pretty sure it's a get.
Instead of trying to hide the username and password in GET or POST parameters, you should instead use Basic authentication, which was invented especially for that purpose and is universally available in clients (and is available using convenience methods in Sinatra).
Also, if you are trying to use REST, you should embrace the concept of resources and resoiurce collections (which is implied by the R and E of REST). So you have a single URL like http://myapi.heroku.com/NearbyPlaces. If you GET there, you gather information about that resource, if you POST, you create a new resource, if you PUT yopu update n existing resource and if you DELETE, well, you delete it. What you should do before is th structure your object space into these resources and design your API around it.
Possibly, you could have a resource collection at http://myapi.heroku.com/places. Each place as a resource has a unique URL like http://myapi.heroku.com/places/123. New polaces can be created by POSTing to http://myapi.heroku.com/places. And nearby places could be gathered by GETing http://myapi.heroku.com/places/nearby?lon=12.343523&lat=56.123533&radius=30. hat call could return an Array or URLs to nearby places, e.g.
[
"http://myapi.heroku.com/places/123",
"http://myapi.heroku.com/places/17",
"http://myapi.heroku.com/places/42"
]
If you want to be truly discoverable, you might also embrace HATEOAS which constraints REST smentics in a way to allows API clients to "browse" through the API as a user with a browser would do. To allow this, you use Hyperlink inside your API which point to other resources, kind of like in the example above.
The params that are part of the url (namely lon, lat and radius) are known as query parameters, the user and password information that you want to send in your form are known as form parameters. In Sinatra both of these type of parameters are made available in the params hash of a controller.
So in Sinatra you would be able to access your lon parameter as params[:lon] and the user parameter as params[:user].
I suggest using basic or digest authentication and a plain GET request. In other words, your request should be "GET /places?lat=x&lon=x&radius=x" and you should let HTTP handle the authentication. If I understand your situation correctly, this is the ideal approach and will certainly be the most RESTful solution.
As an aside, your URI could be improved. Having verbs ("get") and query-like adjectives ("nearby") in your resource names is not really appropriate. In general, resources should be nouns (ie. "places", "person", "books"). See the example request I wrote above; "get" is redundant because you are using a GET request and "nearby" is redundant because you are already querying by location.

Should I still use querystrings for page number, etc, when using ASP.NET 4 URL Routing?

I switched from Intelligencia's UrlRewriter to the new web forms routing in ASP.NET 4.0. I have it working great for basic pages, however, in my e-commerce site, when browsing category pages, I previously used querystrings that were built into my pager control to control paging and now am not sure how to handle this using routing.
I defined a MapPageRoute as:
routes.MapPageRoute("cat-browse", "Category/{name}_{id}", ~/CategoryPage.aspx");
This works great. Now, somebody clicks to go to page 2. Previously I would have just tacked on ?page=2 to the url. How do I handle this using web forms routing? I know I can do something like:
http://www.mysite.com/Category/Arts-and-Crafts_17/page/2
But in addition to page, I can have filters, age ranges, gender, etc.
Should I just keep defining routes
that handle these variables like
above?
Should I continue using querystrings
and if so, how do you define a route
to handle that?
The main reason to use url routing is to expose clean, user-and-SEO-friendly, URLs. If this is your goal, then try to stick to it and not use querystring parameters. Note: I don't believe we need to completely ban the use of querystrings and, depending on your situation, you may decide it best to use querystring parameters for parameters that are not used frequently, or where no real value is added by making the information more semantically meaningful.
So here's what I would do:
Define a catch-all for all your other parameters:
routes.MapPageRoute("cat-browse", "Category/{name}_{id}/{*queryvalues}", "~/CategoryPage.aspx");
In /CategoryPage.aspx, access the router parameter and then parse as appropriate:
Page.RouteData.Values["queryvalues"]
Instead of using the syntax of Arts-and-Crafts_17/**page/2/age/34** for these parameters, I perfer to use the following syntax: Arts-and-Crafts_17/pg-2/age-34/
If you do this, the catch-all parameter 'querystring', will equal pg-2/age-34. You can now easily parse this data and add each name/value to the page context. Note that you will need to do something along these lines since each of these parameters are optional on your site.
You can take advantage of C# 4.0 named and optional parameters. Please have a look at this example from haacked
If you are using a lower version of the framework, you can also use code from the link above. But instead of declaring the method as
public ActionResult Search(int? page=0)
{}
you can declare it as
public ActionResult Search(int? page)
{
if(page == null)
{
page=0;
}
}
HTH

Resources