I am a starter with ASP.NET MVC. I generated a basic class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyPluginProject.Models;
namespace MyPluginProject.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public JsonResult data(TestRequestObject testRequestObject)
{
TestResponseObject respobj = new TestResponseObject();
respobj.id = testRequestObject.Id;
respobj.name = testRequestObject.Name;
//return Newtonsoft.Json.JsonConvert.SerializeObject(respobj);
return Json(respobj);
}
}
}
and the TestRequestObject POCO looks like this:
public class TestRequestObject
{
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
The route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
However when I run this locally and send request from Postman with
curl --location --request POST 'http://localhost:50132/home/data' \
--header 'Content-Type: application/json' \
--data-raw '{
"id": "123456789",
"name": "John Smith",
"address":"ftyrhrrhrhhr"
}'
the value is not getting bound to the TestRequestObject. I tried [FromBody], however it's only allowed for .NET Core it seems. I don't seem to understand as to what is going wrong here.
CodePudding user response:
Try sending POST request this way.
curl -d '{json}' -H 'Content-Type: application/json' https://example.com/login
CodePudding user response:
firstly you should use [Route("api/[controller]/[action]")] Tag in upon of your controller class in order to rout URL to this block of your code
[Route("api/[controller]/[action]")]
public class HomeController : Controller
{
...
secondly you are starter in asp , i suggest you that you use Swagger to generate better ui and help you to send HTTTP request in correct format to Webapplication , for adding swagger to your project follow below :
