繁体   English   中英

如何返回JSON响应对象

[英]How to return JSON response object

即使我按如下方式添加媒体格式化程序,也遇到此错误。 我正在与邮递员进行测试。 邮递员标头的内容类型为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;
    }


}

仅当击中api/v1/pin/initiation的请求内容类型为text/html我才能重现此内容。 您说您的Postman设置被设置为application/json并且主体是x-www-form-urlencoded ,但是从我的测试来看,是否会抛出上面显示的异常。

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM