如何返回JSON响应对象

时间:2019-02-06 05:31:31

标签: c# rest asp.net-web-api postman

即使我按如下方式添加媒体格式化程序,也遇到此错误。我正在与邮递员进行测试。邮递员标头的内容类型为application / json,正文为x-www-form-urlencoded。我该如何解决?

  

“ ExceptionMessage”:“没有MediaTypeFormatter可用于读取   媒体类型为'text / html'的内容中类型为'Initiate'的对象。”,   “ ExceptionType”:“ System.Net.Http.UnsupportedMediaTypeException”

这是我的代码示例:

[RoutePrefix("api/v1/pin")]
public class GameController : ApiController
{

    // POST: api/Game
    [HttpPost, Route("initiation")]
    public async System.Threading.Tasks.Task<Initiate> PurchaseInitiationAsync([FromBody]Initiate value)
    {

        if (value == null)
        {
            var message = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Request is NULL! Please check your data.")),  
                ReasonPhrase = "Request is NULL! Please check your data."
            };

            throw new HttpResponseException(message);
        }

        HttpClient httpClient = new HttpClient();

        HttpContent content = new StringContent(
            JsonConvert.SerializeObject(value),
            Encoding.UTF8,
            "application/json"
        );



        HttpResponseMessage response =
            await httpClient.PostAsync("http://test:1907/purchase_initiation", content);


        var obj = response.Content.ReadAsAsync<Initiate>(
            new List<MediaTypeFormatter>
            {
                new JsonMediaTypeFormatter()
            }).Result;

        return obj;
    }


}

1 个答案:

答案 0 :(得分:0)

仅当命中api/v1/pin/initiation的请求内容类型为text/html时,我才能重现此内容。您说您的邮递员设置设置为application/json,正文设置为x-www-form-urlencoded,但是从我的测试来看,是否会抛出上面显示的异常。

我将通过打开Postman控制台(CTRL + ALT + C)并检查请求标头来仔细检查Postman是否确实发送了正确的内容类型标头。

enter image description here