ASP.NET Core 3.0 Web API - 控制器方法未命中

ASP.NET Core 3.0 Web API - controller method not hit

我是 ASP.NET Core Web 的新手 API - 这是我的控制器方法:

[HttpPost]
[Route("Createnewlead")]
public IActionResult LeadCreate([FromBody]CRM_Lead Lead)
{
    // do stuff
}

这是我的 json:

{
   "RegionID": "1",
   "RunningNo": "1633",
   "CardName": "Google Pte Limited",
   "Telephone": "65748394",
   "Mobile": "89349859",
   "Fax": "47850555",
   "Email": "sre@hotmail.com",
   "ROC": "28IO45h44",
   "OwnerEmail": "huisan@syspex.com"
}

请多多指教!

将您的路线更新为

[Route("api/[Controller]/Createnewlead")]

您的路由当前设置为 [Route("Createnewlead")],这将转换为路由 https://localhost:5001/createnewlead,但您呼叫的是 https://localhost:5001/api/sap/createnewlead

或者 post 到

 localhost:5001/Createnewlead

在您的示例中,您为每个操作设置一个路由,您也可以为每个控制器设置一个路由,例如

[Route("api/[controller]/[action]")]
public class MyController: Controller 
{
}

[Route("[controller]/[action]")]
public class MyController: Controller 
{
}

[Route("[controller]")]
public class MyController: Controller 
{
}

这完全取决于您希望路由的外观

检查你的路由属性和邮递员/浏览器URL,两者完全不同

您的路线属性没有路线 "api/sap/Createnewlead" 它只有 "Createnewlead".

将您的路由属性 url 更改为您想要的 url

我可以使用以下模型(将 RegionID 定义为 int 在 asp.net core 3.0 web api 中重现您的问题(400 错误并且未命中控制器)而不是 string):

public class CRM_Lead
{
    public int RegionID { get; set; }
    public string CardName { get; set; }
    //other properties
}

这是asp.net core 3.0中默认的System.Text.Json造成的

方案一: 更改 post json 以删除 "" 类型为 int

的属性
{
   "RegionID": 1,//instead of "1"
    ....
}

解决方案 2: 保留上面的 json 并通过引用 Json.NET support 在 ASP.NET Core 3.0 项目中使用旧的 Newtonsoft.Json .

1) Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.0.0

2) 添加services.AddControllers().AddNewtonsoftJson();在 startup.cs