Post方法在ASP.NET Core中不起作用

时间:2017-09-12 13:51:28

标签: c# asp.net asp.net-web-api2 asp.net-mvc-routing

我正在尝试创建ASP.NET Core Web API。我有Post / Get方法,如下所示:

    [HttpGet]
    [Route("api/getProffessionByID/{id}")]
    public IHttpActionResult getProffessionByID(Int64 id)
    {
        AllProffession model = new AllProffession();
        try
        {
            var result = model.GetAllProffession.Where(i => i.id == id).FirstOrDefault();
            return Ok(result);
        }
        catch (Exception ex)
        {
            return InternalServerError("Something Went Wrong : " + ex.ToString());
        }
    }

    [HttpPost]
    [Route("api/savePerson")]
    private IHttpActionResult savePerson(PersonModel model)
    {
        try
        {
            if (model.name != string.Empty || model.weight != 0 || model.height != 0 || model.proffession != 0)
            {
                Guid guid = Guid.NewGuid();
                Random random = new Random();
                int i = random.Next();
                model.id = i;
                return Ok(model);
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return InternalServerError("Something Went Wrong : " + ex.ToString());
        }
    }

我的get方法在url和Postman上运行得很好。 enter image description here

我已尝试[FromBody]同样,但它也无效

型号:

public class PersonModel
    {
        public int id { get; set; }
        public string name { get; set; }
        public int weight { get; set; }
        public int height { get; set; }
        public int proffession { get; set; }
    }

WebApiConfig.cs

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { Controllers = "API", id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }

1 个答案:

答案 0 :(得分:8)

也许您应该将方法更改为公开而不是私有

[HttpPost]
[Route("api/savePerson")]
public IHttpActionResult savePerson(PersonModel model) {
    //...
}