Which URL path that would result in a call to getName()? - soa

I have a restful web service that looks like :
#path("/resource")
Class HelloWorld {
#path("/id")
#Get
public String getName() {
return "a name";
}
}
Which of URLs path that would result in a call to getName() ?
resource/id or
resource/id/name

To call getName() you have to do a GET request on /resource/id.

Related

Unsupported Media type 415 #RequestBody Not working But #RequestParam is working

I have a Model class and a controller. I am posting json type data in the body of post man. But each time i'm getting an unsupported media type 415 error.
Here is My Model class :
public class Model1 {
private String name;
private String password;
public Model1() {
System.out.println("In the Model");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "Model1 [name=" + name + ", password=" + password + "]";
}
}
And My Controller is :
#Controller
#ResponseBody
public class EcomController {
#RequestMapping(value="/getLogin", method=RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_VALUE)
public String getLoginStatus(#RequestBody Model1 name){
return "successfully called Post"+name.toString();
}
}
I have used HttpServletRequest in the place of #RequestBody and it worked. But Why its not woking when I am using #RequestBody?
This is the postman snapshot.
Here is the image of request from postman
{
"name": "anshsh",
"password": "vbvfjh"
}
This is the Screen shot of headers used in the request
I found the mistake in my configuration file.
adding <mvc:annotation-driven /> solved the problem.
Explanation :
My program was running well but problem was on Mapping the String (Json) into java objects. So there was some issue in default Mapping classes. Although, jackson was present in class-path, It wasn't working.
<mvc:annotation-driven />
this tag would register the HandlerMapping and HandlerAdapter required to dispatch requests to your #Controllers. In addition, it also applies some defaults based on what is present in your classpath. Such as: Support for reading and writing JSON, if Jackson is on the classpath.
There are two areas to check for such issues.
Add Content-type as application/json in the request (which you
have already done)
Make sure you have jackson (core and data-bind)
libraries in the classpath
The point #2 is to make sure that the application is able to convert between JSON and Java types.
To narrow down the issue further, check the logs and try GET API and see if the Java object is converted to JSON string.
Refer this link for complete working code.
You don't need to put #ResponseBody there
also some example would be
#RestController
public class EcomController {
#PostMapping("/getLogin")
public String getLoginStatus(#RequestBody Model1 name){
return "successfully called Post"+name.toString();
}
}
If you keep getting error, I think the problem is the servlet didn't find your controller registered.. Can you give more information in detail like the log when you try to compile?

How do I retrieve a value in the IMemoryCache by the key provided on the API call

I have been playing around with the .Net Core Web API and have been trying to get the key and value that I have stored in cache. I store it in cache using the following statement:
if (!cache.TryGetValue<string>(store.id, out string failureString))
{
_cache.Set<string>(store.id, store.name);
}
return CreatedAtAction("Get", new { store.id, store.name });
With the JSON:
{
"id":1,
"name":"Tesco"
}
But I am unsure what I need to put in the below method in order to return the id and value depending on what parameter is used on the api call?
[HttpGet("{id}")]
public IActionResult Get(int id)
{
}
Is this at all possible?
Thanks in advance.
I managed to get it to work with the following:
[HttpGet("{id}")]
public IActionResult Get(int id)
{
return Ok(_cache.Get(id));
}

problem in httpdelete request asp.net core 2

Hello i am working on asp.net core 2.2 web api , my get request is working fine but i am having problem in HTTPDELETE request, my code for the delete request is as follows
[Route("api/[controller]")]
[ApiController]
public class PatientController : ControllerBase
{
IPatientManager _patientManager;
IEnumerable<Patient> patientList;
public PatientController(IPatientManager patientManager)
{
_patientManager = patientManager;
}
[HttpGet]
public IEnumerable<Patient> Get()
{
return (patientList = _patientManager.GetAllPatients());
}
// DELETE api/values/5
[HttpDelete("api/Patient/{id}")]
public bool Delete(long id)
{
if (_patientManager.DeletePatient(id))
return true;
else
return false;
}
}
}
when i put the request in URL as localhost:3, n922/api/Patient/444373 it gives me HTTP ERROR 404 , my startup.cs file is using the below code for MapRoute
app.UseMvc(opt =>
{
opt.MapRoute("Default",
"{controller=Patient}/{action=Get}/{id?}");
});
to start the my PatientController instead of ValuesController, Please help what is problem where i am doing wrong? TIA
You have a route prefix defined on your controller as api/[controller], which translates to /api/Patient. Then, your route on your action is defined as api/Patient/{id}, which makes the entire route to this action: /api/Patient/api/Patient/{id}. That's obviously not right and is the source of your 404. Change the route to just {id}.
[HttpDelete("{id}")]
public bool Delete(long id)

How do i get the requestmapping value in the controller?

In the controller , i have this code,
somehow, i want to get the request Mapping value "search".
How is it possible ?
#RequestMapping("/search/")
public Map searchWithSearchTerm(#RequestParam("name") String name) {
// more code here
}
If you want the pattern, you can try HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE:
#RequestMapping({"/search/{subpath}/other", "/find/other/{subpath}"})
public Map searchWithSearchTerm(#PathVariable("subpath") String subpath,
#RequestParam("name") String name) {
String pattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
// pattern will be either "/search/{subpath}/other" or
// "/find/other/{subpath}", depending on the url requested
System.out.println("Pattern matched: "+pattern);
}
It seems you are looking for the path that this request has matched, then you can directly get it from servlet path
#RequestMapping("/search/")
public Map searchWithSearchTerm(#RequestParam("name") String name, HttpServletRequest request) {
String path = request.getServletPath();
// more code here
}
Having a controller like
#Controller
#RequestMapping(value = "/web/objet")
public class TestController {
#RequestMapping(value = "/save")
public String save(...) {
....
}
}
You cant get the controller base requestMapping using reflection
// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
or the method requestMapping (from inside a method) with reflection too
//Method requestMapping
String methodMapping = new Object(){}.getClass().getEnclosingMethod().getAnnotation(RequestMapping.class).value()[0];
Obviously works with an in requestMapping single value.
Hope this helps.
#RequestMapping("foo/bar/blub")
public Map searchWithSearchTerm(#RequestParam("name") String name, HttpServletRequest request) {
// delivers the path without context root
// mapping = "/foo/bar/blub"
String mapping = request.getPathInfo();
// more code here
}
For Spring 3.1 and above you can use ServletUriComponentsBuilder
#RequestMapping("/search/")
public ResponseEntity<?> searchWithSearchTerm(#RequestParam("name") String name) {
UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest();
System.out.println(builder.buildAndExpand().getPath());
return new ResponseEntity<String>("OK", HttpStatus.OK);
}

Pass a JSON array to a WCF web service

I am trying to pass a JSON array to a WCF service. But it doesn't seem to work. I actually pulled an array [GetStudents] out the service and sent the exact same array back to the service [SaveStudents] and nothing (empty array) was received.
The JSON array is of the format:
[
{"Name":"John","Age":12},
{"Name":"Jane","Age":11},
{"Name":"Bill","Age":12}
]
And the contracts are of the following format:
//Contracts
[DataContract]
public class Student{
[DataMember]public string Name { get; set; }
[DataMember]public int Age{ get; set; }
}
[CollectionDataContract(Namespace = "")]
public class Students : List<Student>
{
[DataMember]public Endorsements() { }
[DataMember]public Endorsements(IEnumerable<Student> source) : base(source) { }
}
//Operations
public Students GetStudents()
{
var result = new Students();
result.Add(new Student(){Name="John",12});
result.Add(new Student(){Name="Jane",11});
result.Add(new Student(){Name="Bill",12});
return result;
}
//Operations
public void SaveStudents(Students list)
{
Console.WriteLine(list.Count); //It always returns zero
}
It there a particular way to send an array to a WCF REST service?
I had similar issue.
I was calling the service from a browser and the problem was Firefox dynamically changing the request content-type from 'application/json' to 'application-json;charset=utf-8'.
If you are calling the service from a browser, test it with non-firefox browser and if that was the case you need to remove the charset from the request content-type header

Resources