How to call the WebApi,Implemented with AttributeRouting for each action methods,calling it from my client and passing the Query parameters in url? - asp.net-web-api

I have implemented attribute routing for each of action methods in My Webapi.
Example of action method is:-
[Route("api/DocumentApi/DeleteDocument/{fileInfoId}/{customerAccountName}")]
[HttpDelete]
public HttpResponseMessage DeleteDocument(int fileInfoId, string customerAccountName)
{
//***
//*** Some body contents
//***
}
Now i want to call the above action method from the client example( Fiddler Web debugger),or browser and want to pass the Url request in the below pattern:-
http://{localhost:9791}/api/DocumentApi/DeleteDocument?fileInfoId=12&customerAccountName="Manish"
Currently i am not able to hit the above action method by the above specified url request.
But if i use the url pattern like below:-
http://{localhost:9791}/api/DocumentApi/DeleteDocument/12/Manish
I am able to hit the above action method.But for my project requirement,I need to use the Url with query parameters only.
Please suggest me the approach,how to achieve this?
Any response will be greatly appreciated.

Route templates in Web API do not support specifying query string parameters. For your scenario, do not define fileInfoId and customerAccountName as part of your route template as doing so makes Web API to strictly look for 5 segments(the text between the / characters in your route template) in your request url...so just modify your route template to [Route("api/DocumentApi/DeleteDocument")] and keep the parameters on the actions as it is...

Use like following code :
[Route("api/DocumentApi/DeleteDocument/{fileInfoId}/{customerAccountName}")]
public HttpResponseMessage TestAction(string fileInfoId,string customerAccountName)
{

Related

How to get the current Request Mapping URL configured at Controller layer when request is executed?

I went through so many links like How to show all controllers and mappings in a view and How to configure a default #RestController URI prefix for all controllers? and so on.
I want to get the Request Mapping URL at Filter interceptor
Ex: This URL I configured at REST controller method, and naturally we will pass /employees/employee-names/John to get the Employee John.
/employees/employee-names/{employee_name}
Now, when somebody hit /employees/employee-names/John I want to get the value of actual mapping url if REST controller /employees/employee-names/{employee_name},
Any pointers how to get that ?
Spring MVC sets the attribute HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, which you can use to get the pattern that was used to match the incoming request:
String matchingPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)
That would return /employees/employee-names/{employee_name} in your case.
I was able to solve this issue using below code. AntPathMatcher is the perfect way to identify if the incoming request and URL you configured in the property file matches exactly. This solution works greatly for me.
AntPathMatcher springMatcher = new AntPathMatcher();
Optional<String> antMatch = props.getMapping().stream()
.filter(//Perform Some Filter as per need)
.map(Mapping::getVersion)
.findFirst();
return antMatch.isPresent() ? antMatch.get() : null;

Redirect in controller using RedirectToAction malfunction

Normally google is my best friend but this problem I can't figure out or even understand.
I have an action in my controller that I use for selecting which follow up action in my controller to use, based on user input (see image)
This redirect work like a charm, it's when the action I'm redirected to is finished as the problem arises. In my action I fetch some much needed data for the web site. When tha data is fetched the action are supposed to redirect to a generic action, that in turn will present my view. The "middleware" action redirect correctly and it also send the parameters but the "recieving action" don't handle or recieve the parameters.
I'm totally clueless here, is it not possible to redirect to an action that in turn redirect to another action or what is the problem?
The route specification looks a bit odd.
I think it should be possibly:
[HttpGet("Customer/Device/{id}")]
public IActionResult Device(string id, bool like)
{
}
Now the URL it tried to redirect you to should work. Id from URL, and the like parameter from query.
If you want both in URL:
[HttpGet("Customer/Device/{id}/{like}")]
public IActionResult Device(string id, bool like)
{
}

Codeigniter router get parameter

I use $.getJSON() to retrieve some data for a couple of cascading dropdowns in my form. $.getJSON() automatically appends the parameter at the end of the URL like domain.com/controller/method/?parent=5
So, I've declared my method like public function method($parent) which works file, but the same method will be used from other parts of the website that will call it like domain.com/controller/method/5
I tried to create a route in routes.php like the one below:
$route['business/regions/?parent=(:num)'] = 'business/regions/$1';
but it doesn't seem to work. Am I doing something wrong? Maybe ? is confusing the regex parser of the router? Do I have to escape it somehow to make it a 'literal' ? ?
Or is it that router is not used to 'rewrite' get parameters at all? I'm very confused, as it should work but it doesn't and I'm wondering what's wrong with it...
Codeigniter route parameters are for url parameters. It is particularly useful when trying to create a REST styled url pattern.
What you're trying to do is get url query string from the url which is not supported via the Codeigniter router. For you to get what you want you can do the following:
In your routes.php:
$route['business/regions'] = 'business/regions';
and in your controller Business.php:
public function regions() {
//the numeric id you're looking for
$parent = $this->input->get('parent');
}

Spring 4 #RequestMapping handling REST URL with special characters

How does Spring 4 handle the REST URL with special character, such as #?
For example : http://localhost:8080/#/members/browse?id=1234
The following code seems not working.
Because Spring always discards everything after (including) #, and just returns the response of http://localhost:8080
Could anyone give us some help?
#RequestMapping(value = "/#/members/browse", method = RequestMethod.GET, produces = "application/json")
public String findMembers(#RequestParam(value="id", required=false) {
// some code
}
This is the expected behavior. It's a fragment identifier and it's not meant to be used for routing requests on the server side.
In your browser, clicking on another anchor link like #/members/browse?id=5678 in the same page looks for an anchor within the page and does not send a request to the server.
I think you're probably using a javascript framework such as Ember or Angular, which provide routing components to route those events on the client side and render views. See the router documentation for Ember.

Make the route parameter actually appear in the address bar

I have a tiny application in MVC 3.
In this tiny application, I want my URLs very clear and consistent.
There's just one controller with one action with one parameter.
If no value is provided (that is, / is requested by the browser), then a form is displayed to collect that single value. If a value is provided, a page is rendered.
The only route is this one:
routes.MapRoute(
"Default",
"{account}",
new { controller = "Main", action = "Index", account = UrlParameter.Optional }
);
This all works fine, but the account parameter never appears in the address line as a part of the URL. I can manually type test.com/some_account and it will work, but other than that, the account goes as a post parameter and therefore does not appear. And if I use FormMethods.Get in my form, I get ?account=whatever appended to the URL, which is also not what I want and which goes against my understanding. My understanding was that the MVC framework would try to use parameters set in the route, and only if not found, it would append them after the ?.
I've tried various flavours of setting the routes -- one route with a default parameter, or one route with a required parameter, or two routes (one with a required parameter and one without parameters); I've tried mixing HttpGet/HttpPost in all possible ways; I've tried using single action method with optional parameter string account = null and using two action methods (one with parameter, one without), but I simply can't get the thing appear in the URL.
I have also consulted the Steven Sanderson's book on MVC 3, but on the screenshots there are no parameters either (a details page for Kayak is displayed, but the URL in the address bar is htpp://localhost:XXXX/).
The only thing that definitely works and does what I want is
return RedirectToAction("Index", new { account = "whatever" });
But in order to do it, I have to first check the raw incoming URL and do not redirect if it already contains an account in it, otherwise it is an infinite loop. This seems way too strange and unnecessary.
What is the correct way to make account always appear as a part of the URL?
My understanding was that the MVC framework would try to use
parameters set in the route, and only if not found, it would append
them after the ?
Your understanding is not correct. ASP.NET MVC doesn't append anything. It's the client browser sending the form submission as defined in the HTML specification:
The method attribute of the FORM element specifies the HTTP method used
to send the form to the processing agent. This attribute may take two
values:
get: With the HTTP "get" method, the form data set is appended to the URI specified by the action attribute (with a question-mark ("?")
as separator) and this new URI is sent to the processing agent.
post: With the HTTP "post" method, the form data set is included in the body of the form and sent to the processing agent.
ASP.NET MVC routes are used to parse an incoming client HTTP request and redispatch it to the corresponding controller actions. They are also used by HTML helpers such as Html.ActionLink or Html.BeginForm to generate correct routes. It's just that for your specific scenario where you need to submit a user entered value as part of the url path (not query string) the HTML specification has nothing to offer you.
So, if you want to fight against the HTML specification you will have to use other tools: javascript. So you could use GET method and subscribe to the submit handler of the form and inside it manipulate the url so the value that was appended after the ? satisfy your requirements.
Don't think of this as ASP.NET MVC and routes and stuff. Think of it as a simple HTML page (which is what the browser sees of course) and start tackling the problem from that side. How would you in a simple HTML page achieve this?

Resources