'How to process .Net Core API response in a pretty way?
I have test API (.NET5) with one method for HttpGet and one method for HttpPost. When I do call the API from simple .html page as on example below, my browser is redirected to API call address and only text is diplayed. What I do want to do instead is call API > get response form it > process the response in the same page that called API.
What would be the proper way to achieve this? I can think of using return Redirect() from API and provide a result message as url parameter that can be processed, but user would see ugly URL in address bar. Do I need to make API call with Javascript behind the curtains and process the response on client side? Or is there some ActionResult derived class that allows to pass data back to caller, considering caller is a plain .html page and not a razor page view etc.
To be specific. User uploads a file, something gets wrong and this is the result. How to change this to let's say a text inside a HTML element targeted by ID, which is present on the page that triggered API call?
API code
[ApiController]
[Route("[controller]")]
public class TestController : Controller
{
[HttpGet("SayHi")]
public ActionResult Greetings()
{
return Ok("Hi!");
}
[HttpPost("UserFileUpload")]
public ActionResult UploadFile(IFormFile uploadFile)
{
if (uploadFile == null || uploadFile.Length <= 0)
return BadRequest("File might be corrupted or no file was uploaded.");
return Ok();
}
}
.html page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>Hello</h1>
<form action="https://localhost:44398/Test/UserFileUpload" method="post" enctype="multipart/form-data">
<a href="https://localhost:44398/Test/SayHi">Execute get API method</a>
<br />
<br />
<input type="file" id="upFile" name="uploadFile" />
<input type="submit" value="Send form data to API" />
</form>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

