我正在尝试从Postman调用C#api端点。我正在从有效的代码中简化代码:
url: https://localhost:44302/api/MyControllerName/MyMethodName
Method: Post
Headers:
Content-Type: application/json
Accept: application/json
Body: {"ids": "1234asdfasdfasdf3e"}
和我的控制器代码:
[HttpPost]
[Route("api/MyControllerName/MyMethodName")]
public async Task PostNewIds([FromBody] string ids)
{ // <-- breakpoint here is never hit
var json = JsonConvert.SerializeObject(ids);
Debug.WriteLine(json);
}
但是我在VS中遇到此错误,无法达到在大括号处设置的断点
{"Unexpected character encountered while parsing value: {. Path '', line 1, position 1."}
答案 0 :(得分:1)
在您的PostNewIds
操作中,您正在将请求正文反序列化为string
参数,因此您的ids == @"{""ids"":""1234asdfasdfasdf3e""}"
也是如此。如果您需要从请求中获取ids
的值,则可以添加模型:
public class MyMethodNameModel
{
public string Ids { get; set; }
}
现在您可以在操作中使用此模型:
[HttpPost, Route("api/MyControllerName/MyMethodName")]
public async Task PostNewIds([FromBody] MyMethodNameModel model)
{
Debug.WriteLine(model.Ids);
}
或(如果需要),您可以使用@Hasan建议并反序列化“手动”:
[HttpPost, Route("api/MyControllerName/MyMethodName")]
public async Task PostNewIds([FromBody] string body)
{
var obj = JsonConvert.DeserializeObject(ids) as JObject;
var val = obj["ids"] as JValue;
Debug.WriteLine(val.Value);
}