2017-09-12 129 views
-1

我正在嘗試創建ASP.NET Core Web API。我有郵政/獲取方法,按照以下:Post Method在ASP.NET Core中不工作

[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以及郵差無一不精。 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")); 
     } 
+0

您的PersonModel的外觀如何? – jhen

+0

如果我在Post方法中使用FromBody,我得到了同樣的錯誤,我在截圖 –

+0

中顯示的是'Controllers'是否正確?或者它應該是你的路由配置中的'controller' – JamieD77

回答

5

也許您應該將您的方法更改爲public而不是private

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

將方法聲明爲私有是愚蠢的。我沒有注意到我寫了私人方法。感謝幫助。 另外,非常感謝Niladri和Nkosi讓我覺得我的方向是錯誤的。我將開始學習ASP.NET核心api。 –