Several GET Methods in ASP .NET WEB API causing 500 when sending array using URI - angularjs

In my ASP .NET WEB API, I want to use the following methods:
[Route(""), HttpGet]
public IDictionary<int, string> GetAll()
{
//doSth
}
[Route(""), HttpGet]
public IDictionary<int, string> GetSpecificOnes([FromUri]IEnumerable<int> carsIds)
{
//doSth
}
When requesting the second one using angular, I get the following exception:
angular.js:12011 GET http://localhost:12345/_api/cars?&carsIds[0]=1&carsIds[1]=2&carsIds[2]=5 500 (Internal Server Error)
I think the problem is, that I have two GET-Methods without a route. But I don't need one. How do I solve this problem?

You actually don't need to define a route, like you say, as long as the GET methods in the controllers have different signatures and parameterlist.
The problem in your case is that you call the method the wrong way.
Either change the parameter name in the api method to carsIds or change the angular HTTP query string to ?ids[0]=1&ids[1]=2&ids[2]=5

Related

Optional response body for rest client using RESTEasy

I'm writing a POC for Quarkus. I'm using this quick start guide to build a REST client. The REST service I'll be integrating with is third party. Here is a simple example of my current implementation:
#Path("/v1")
#RegisterRestClient
public class EmployeeApi {
#POST
#Path("/employees")
ApiResponse createEmployee(#RequestBody Employee employee)
}
This works fine. The issue I'm having is that the third party API will, depending on success / failure, return a response body. In the scenario it does fail, it provides details in the response body (ApiResponse) on why it was unsuccessful. When it succeeds, it returns nothing. This causes Quarkus to throw the following exception:
javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/octet-stream and type com.test.app.ApiResponse
I've tried to wrap ApiResponse in an Optional type but does not solve the problem. I see absolutely nothing in Quarkus / RESTEasy documentation that would indicate a work-around.
I'm wondering if I should be using javax.ws.rs.core.Response instead.
The problem is JaxRS tries to fit ApiResponse to a default return type being application/octet-stream
You should make sure to specify explicitly that you're returning application/json
This is possible using #Produces(APPLICATION_JSON) on top of your service.
Here is the correct code snippet
#Path("/v1")
#RegisterRestClient
public class EmployeeApi {
#POST
#Path("/employees")
#Produces(APPLICATION_JSON)
ApiResponse createEmployee(#RequestBody Employee employee)
}

Spring React and Sessions.. how to keep session

I have set up my spring to maintain a HTTP session on an object like so:
#Component
#SessionScope
public class Basket { .. }
controller:
#PostMapping(path="/basket/addItem/{user}", consumes = "application/json", produces = "application/json")
public Basket createBasket(#PathVariable String user, #RequestBody Item item) {
System.out.println("POSTING..................................");
return basketService.addItem(user, item);
}
now when i use a REST client, in firefox i can see that the session bean is created and maintained for the duration - multiple calls. I can append to the object. If i try another client, it gets its own session with its own bean. great..
spring logs the following:
Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [269] milliseconds.
However im trying to create a basic front end in react, when react makes a request using axios it gets a new bean every time, which means that the session must be ending after each call. IS that correct? or im not tying it to the react application...
Maybe the approach im taking is not correct, maybe i should use a a different approach, Im trying to learn about spring boot, so its a basic project... and right now i want to maintain user session for a cart. so subsequent calls i can append to the object...
by adding the following to my controller it all began to work.
#CrossOrigin(origins = { "http://localhost:3000" }, allowedHeaders = "*", allowCredentials = "true")

Can i call a method call before executing my Rest API which is coming from Angular

Can i call a method before executing my Rest API which are coming from Angular I am making a post rest call (predefined API from activiti) from angular and i need to call a method before executing the rest API based on the method response i have to decide either i have to call the API or not .Can i use spring AOP? please provide your suggestions and give me any reference links so that i can go head with the implementation
[POST] http://localhost:8080/myapp/test
before this rest call i have to call a method based on the response i have to decide whether i have to call api or not[some how i traps my request and then navigate to the api]
Continuing from the comments, #Narendra, you dont have to modify your controller, what I meant is create a aspect like this
#Pointcut("#annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void requestMapping() {}
#Pointcut("within(de.some.package.controller.*) || within(de.some.package.aspect.*)")
public void myController() {}
#Around("requestMapping() && myController()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
//This will be called before and after any method in the package controller or any method with #RequestMapping annotaion is called
Object result= joinPoint.proceed();
}
This is around advice, which give you more control over the method call. You can also use #Before.
This is done from Java Annotations. I am sure you can do the same from xml as well. Here are a few examples.
http://howtodoinjava.com/spring/spring-aop/aspectj-before-advice-example/
https://www.mkyong.com/spring/spring-aop-examples-advice/

Web api is giving error on passing * as the input value to the api method parameter

I am using asp.net mvc web api and i have this method
[HttpGet]
public LoginResult AuthenticateOnlineBookingUser(String userName,String password)
{
//My Code
}
The problem is that when i pass (*) as input value to the parameter (password)
i receieve this error but on other inputs it is working perfectly
A potentialy dangerous Request.Path.value was detected from client(*)
Thanks in advance
Note:My client side is written in angular js
i tried this solution as well Getting "A potentially dangerous Request.Path value was detected from the client (&)" but it is not working for me
You need to set the options for invalid characters. You can do this in your web.config as shown here.
Use url encoder to encode the request before sending it to server.
Finally solved my problem by changing my GET request to POST request The problem was with query string in Order to solve it with GET Request i have to make some changes to my query string in order to make it work but

How to know if a Kohana request is an internal one?

I'm writing an API using Kohana. Each external request must be signed by the client to be accepted.
However, I also sometime need to do internal requests by building a Request object and calling execute(). In these cases, the signature is unnecessary since I know the request is safe. So I need to know that the request was internal so that I can skip the signature check.
So is there any way to find out if the request was manually created using a Request object?
Can you use the is_initial() method of the request object? Using this method, you can determine if a request is a sub request.
Kohana 3.2 API, Request - is_initial()
It sounds like you could easily solve this issue by setting some sort of static variable your app can check. If it's not FALSE, then you know it's internal.
This is how I ended up doing it: I've overridden the Request object and added a is_server_side property to it. Now, when I create the request, I just set this to true so that I know it's been created server-side:
$request = Request::factory($url);
$request->is_server_side(true);
$response = $request->execute();
Then later in the controller receiving the request:
if ($this->request->is_server_side()) {
// Skip signature check
} else {
// Do signature check
}
And here is the overridden request class in application/classes/request.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Request extends Kohana_Request {
protected $is_server_side_ = false;
public function is_server_side($v = null) {
if ($v === null) return $this->is_server_side_;
$this->is_server_side_ = $v;
}
}
Looking through Request it looks like your new request would be considered an internal request but does not have any special flags it sets to tell you this. Look at 782 to 832 in Kohana_Request...nothing to help you.
With that, I'd suggest extending the Kohana_Request_Internal to add a flag that shows it as internal and pulling that in your app when you need to check if it is internal/all others.
Maybe you are looking for is_external method:
http://kohanaframework.org/3.2/guide/api/Request#is_external
Kohana 3.3 in the controller :
$this->request->is_initial()
http://kohanaframework.org/3.3/guide-api/Request#is_initial

Resources