尝试从邮递员拨打电话失败,但可通过应用程序使用

时间:2018-12-25 05:17:59

标签: c# json api postman

我正在尝试从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."}

enter image description here

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);
}