我已經構建了一個 Restful-API Java(SpringBoot) 并創建了所需的請求。
以下請求是用于添加新類別的 POST 請求。
我已經測驗了 POSTMAN 的 POST 請求,它按預期作業。
我正在 ASP.NET 5.xx 中構建客戶端 現在,當我呼叫 post 請求時出現問題,API 似乎沒有收到從客戶端發送的資料(@RequestBody 類別)。
這是我如何在服務器端創建它們的簡單代碼:
@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)));
}
客戶端
[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");
}
我不知道那里有什么問題,有人可以幫忙!
編輯 - 這是郵遞員的請求

編輯
我創建了另一個 POST 請求,但作為 RequestParam 而不是 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));
}
并在客戶端創建請求如下
[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?
uj5u.com熱心網友回復:
從 JSON 物件決議時,Jackson 決議器需要一個空的建構式,因此您的類 CategoryDTO 中可能缺少一個空的建構式。
uj5u.com熱心網友回復:
我想您的 Spring Boot 應用程式只是阻止了 POST 請求,因為您沒有提供如何處理請求的說明。嘗試像這里一樣禁用 csrf 保護:https ://stackoverflow.com/a/48935484/13314717
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371721.html
標籤:java c# asp.net rest client-server
