【问题标题】:Post Method is not working in ASP.NET CorePost 方法在 ASP.NET Core 中不起作用
【发布时间】:2018-02-21 00:37:17
【问题描述】:

我正在尝试创建 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 中都可以正常工作。

我也尝试过 [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"));
        }

【问题讨论】:

  • 你的 PersonModel 看起来怎么样?
  • 如果我在 post 方法中使用 FromBody,我会收到与屏幕截图中显示的相同的错误
  • Controllers 正确吗?或者在你的路由配置中应该是controller
  • @UbiquitousDevelopers 您正在混淆核心和 web api 2 的代码。它是什么
  • @UbiquitousDevelopers 到目前为止显示的所有代码都是针对 web api 2

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


【解决方案1】:

也许您应该将方法更改为 public 而不是 private

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

【讨论】:

  • 将方法声明为私有的我很愚蠢。我没有注意到我写了私有方法。感谢帮助。另外,感谢 Niladri 和 Nkosi 让我意识到我走错了路。我会从头开始学习 ASP.NET core api。
猜你喜欢
  • 2022-08-21
  • 1970-01-01
  • 2019-09-17
  • 2020-05-17
  • 2020-03-30
  • 1970-01-01
  • 2015-06-06
  • 2017-01-28
  • 1970-01-01
相关资源
最近更新 更多