skip to Main Content

I have built a Restful-API Java(SpringBoot) and created the needed requests.

The following request is a POST Request to add new Category.

I have tested the POST request by POSTMAN, and it working as expected.

I am building the client-side in ASP.NET 5.x.x.
Now the problem appear when I am calling the post request, it seems the API doesn’t receive the data (@RequestBody category) that has been send from the client.

Here is a code simple of how I have created them
Server Side:

@ResponseStatus(HttpStatus.CREATED)
@PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public CategoryDTO create(@RequestBody CategoryDTO category) {
    log.info("Adding new Category Name: " + category.getName());
    return categoryMapper.asCategoryDTO(categoryService.save(categoryMapper.asCategory(category)));
}

Client Side

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Category category)
{
    Category newCategory = new Category();

    // Serialize the concrete class into a JSON String
    var stringPayload = JsonConvert.SerializeObject(category);
    // Wrap the JSON inside a StringContent which then can be used by the HttpClient class
    StringContent content = new StringContent(stringPayload);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    using (var httpClient = new HttpClient())
    {
                
        using (var response = await httpClient.PostAsync("http://localhost:8080/category/add", content))
        {
                    
            string apiResponse = await response.Content.ReadAsStringAsync();
            newCategory = JsonConvert.DeserializeObject<Category>(apiResponse);
        }
    }

    return RedirectToAction("Index");
}

I don’t know what is wrong there, could anybody help!

EDIT–
Here is the request via postman
postman POST request


EDIT

I have created another POST request but as a RequestParam instead of RequestBody

@ResponseStatus(HttpStatus.CREATED)
    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
    public CategoryDTO addCategory(@RequestParam(name = "categoryName") String categoryName){
        return categoryMapper.asCategoryDTO(categoryService.addCategory(categoryName));
    }

and created in the client side the request as following

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Category category)
{
    Category newCategory = new Category();
    var parameters = new Dictionary<string, string> { { "categoryName", category.Name } };
    var encodedContent = new FormUrlEncodedContent(parameters);

    using (var httpClient = new HttpClient())
    {
        using (var response = await httpClient.PostAsync("http://localhost:8080/category/add", encodedContent))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            newCategory = JsonConvert.DeserializeObject<Category>(apiResponse);
        }
    }

    return RedirectToAction("Index");
}

And It’s works fine!
So the problem is how to pass the data via the httpClient, which need to be of type RequestBody (the data in the body not in the header!) also as a application/json.

So how to pass the data?

2

Answers


  1. I suppose that your spring boot application just blocks POST request because you didn’t provide instruction how to handle requests. Try to disable csrf protection like it did here: https://stackoverflow.com/a/48935484/13314717

    Login or Signup to reply.
  2. It might be a problem in the naming convention. Starting with capital letters in properties in C#, and starting with lowercase in Java.
    If your class looks like this in C#

    class Category {
        int Id;
        string Name;
        ...
    }
    

    And like this in Java

    class Category {
        int id;
        string name;
        ...
    }
    

    It is not going to work so you have to match the property names. So make either both id or both Id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search