I'm building a web API and I want to consume it through an MVC view. The API controller is to insert the user data and the MVC controller is to create the view. I have been looking for information and this is what I have been able to do with that information.
So, the API controller, simply inserts the data to the database through an stored procedure, I've tested with Postman and works fine:
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IActionResult post(Models.Request.UserModel model)
{
using (Models.AdminOrchardContext db = new Models.AdminOrchardContext())
{
Models.UserModel oUsuar = new Models.UserModel();
Models.OrchardTable tOrchard = new Models.OrchardTable();
oUsuar.Name = model.Name;
oUsuar.Email = model.Email;
tOrchard.OrchardLocation = model.OrchardLocation;
var uName = new SqlParameter("@name", oUsuar.Name);
var uEmail = new SqlParameter("@email", oUsuar.Email);
var hOrchardLocation = new SqlParameter("@OrchardLocation", tOrchard.OrchardLocation);
var idUserReg = db.Usuarios.FromSqlRaw("Exec UserAndOrchardInsert @name, @email" +
"@OrchardLocation",
new[] { uName, uEmail, hOrchardLocation});
db.SaveChanges();
}
return Ok();
}
}
The MVC controller where the view is added, from here the API is used with the user data on the view:
[HttpPost]
public IActionResult post(Models.Request.User model)
{
HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri("https://localhost:44325/api/User");
var addRecToDB = hc.PostAsJsonAsync<Models.Request.User>("User", model);
addRecToDB.Wait();
ViewBag.message = "Ok!";
return View();
}
And the view:
@model Huerbog.Models.Request.User
@{
ViewData["Title"] = "post";
}
<h1>User registration</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<h4>Orchard-related field</h4>
<div class="form-group">
<label asp-for="OrchardLocation" class="control-label"></label>
<input asp-for="OrchardLocation" class="form-control" />
<span asp-validation-for="OrchardLocation" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
<h4>@ViewBag.message</h4>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Now, the problem is that when I open the view, even when the API is running, on the page appears the Error 405, I don't know what or where exactly is the error.