【发布时间】:2021-07-19 18:01:37
【问题描述】:
我是新来的 Requestbody 发送表单数据,其中包括从我的手机媒体上传图像和一些字符串格式的数据。我在 Postman 中使用过它并且它正在工作,但在我的应用程序中我遇到了一个问题,即在将数据发布到 API 时它会发出 400 个错误请求。这是我的代码。任何帮助都可以
这是我的后端 api 代码。
[HttpPost]
public ActionResult<FishReadDTO> CreateFish([FromForm] FishCreateDTO fishCreateDTO)
{
var fishmodel = _mapper.Map<Fish>(fishCreateDTO);
if(fishCreateDTO.ImageFile.Length > 0 || fishCreateDTO.ImageFile != null)
{
string apiServerAddress = _httpContextAccessor.HttpContext.Request.Scheme + "://"
+ _httpContextAccessor.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString()
+ ":" + _httpContextAccessor.HttpContext.Connection.LocalPort;
try
{
if(!Directory.Exists(_webHostEnvironment.WebRootPath + "\\images\\"))
{
Directory.CreateDirectory(_webHostEnvironment.WebRootPath + "\\images\\");
}
using (FileStream filestream = System.IO.File.Create(_webHostEnvironment.WebRootPath + "\\images\\" + fishCreateDTO.ImageFile.FileName))
{
fishCreateDTO.ImageFile.CopyTo(filestream);
filestream.Flush();
fishmodel.Image = apiServerAddress + "/images/" + fishCreateDTO.ImageFile.FileName;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error Occured {ex.Message}");
}
}
_repository.CreateFish(fishmodel);
var fishRead = _mapper.Map<FishReadDTO>(fishmodel);
return CreatedAtRoute(nameof(GetFishById), new{Id = fishRead.ID}, fishRead);
}
这是我的 Fish Create DTO。
public class FishCreateDTO
{
[Required]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(100)]
public string Description { get; set; }
[Required]
public float WeightKg { get; set; }
[Required]
public int Stock { get; set; }
[Required]
public float Price { get; set; }
[Required]
public int CategoryID { get; set; }
[Required]
public int UserID { get; set; }
public IFormFile ImageFile {get; set;}
}
对于前端,我使用的是android Kotlin,它也涉及Retrofit2。
这里是api调用
@Multipart
@POST("/efishing-api/fish")
suspend fun createFish(
@Part("name") name: String,
@Part("description") description : String,
@Part("weightKG") weightKG: String,
@Part("stock") stock : String,
@Part("price") price : String,
@Part("categoryID") categoryID: String,
@Part("userID") userID : String,
@Part imageFile : MultipartBody.Part
) : FishCreateResponse
这里是存储库。
suspend fun createFish(
name : String,
description : String,
weightKG : String,
stock : String,
price : String,
userId: String,
categoryId: String,
imageFile : MultipartBody.Part
) : FishCreateResponse {
return RetrofitBuilder.apiService.createFish(
name,
description,
weightKG,
stock,
price,
categoryId,
userId,
imageFile
)
}
这是我正在使用的视图模型
fun createFish(
name : String,
description : String,
weightKG : String,
stock : String,
price : String,
userId: String,
categoryId: String,
imageFile : MultipartBody.Part
) {
CoroutineScope(IO).launch {
val fishCreate = fishRepository.createFish(
name,
description,
weightKG,
stock,
price,
categoryId,
userId,
imageFile
)
}
}
这是我尝试上传表单数据的地方
val file = File(filePath)
val requestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
fishViewModel.createFish(
Fishname.text.toString(),
Description.text.toString(),
FishPrice.text.toString(),
Weight.text.toString(),
Stock.text.toString(),
categoryID.toString(),
userId.toString(),
MultipartBody.Part.createFormData("imageFile", file.name, requestBody)
)
这里是日志
2021-07-20 01:49:31.117 24404-25371/com.example.efishingapp E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-3
Process: com.example.efishingapp, PID: 24404
retrofit2.HttpException: HTTP 400 Bad Request
at retrofit2.KotlinExtensions$await$2$2.onResponse(KotlinExtensions.kt:53)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:161)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
*更新(我的改造)
@Multipart
@POST("/efishing-api/fish")
suspend fun createFish(
@Part("name") name: String,
@Part("description") description : String,
@Part("weightKG") weightKG: String,
@Part("stock") stock : String,
@Part("price") price : String,
@Part("categoryID") categoryID: String,
@Part("userID") userID : String,
@Part imageFile : MultipartBody.Part
) : FishCreateResponse
任何解决方案都可以。谢谢
【问题讨论】:
-
请尝试验证是否有任何用于 Api 的注释,如 POST 或 PUT,或者您可以检查或错误的请求参数或 api 路径问题可能是空间......只是检查希望它可以帮助你跨度>
-
谢谢!。我刚刚检查了我的改造。这是正确的并且坚持 POST 没有空格什么的。此外,api路径之间没有空格
-
另外请验证您发送的请求参数,例如文件或地图或密钥等。
-
我已经更新了问题的内容。我的应用程序中使用的 Retrofit API 类包含映射到我的 FishCreateDTO 的请求参数。
-
您能否检查您的 BASEURL 是否包含任何空格或 / 行内,或者只是将 baseurl 的最后 2-3 个字符放在这里
标签: android android-studio asp.net-core kotlin retrofit2