当我点击google对话流的端点时,c#中出现错误,但相同的google对话流端点在postman中工作

当我点击google对话流的端点时,c#中出现错误,但相同的google对话流端点在postman中工作,c#,postman,C#,Postman,我在PostMan中使用此端点:- 我要发送的JSON字符串:- {"query":"flights from NYC to Vadodara","sessionId":"6b9d4676-2a71-4c64-a562-8c08f198c623","lang":"pt-BR","resetContexts":false} 我正在邮递员中设置内容类型和授权 所有这些东西在postman中都可以完美地工作,但问题是,当我使用c#代码访问此端点时,代码不工作,请给出以下错误:- 我得到的错误是:-

我在PostMan中使用此端点:-

我要发送的JSON字符串:-

{"query":"flights from NYC to Vadodara","sessionId":"6b9d4676-2a71-4c64-a562-8c08f198c623","lang":"pt-BR","resetContexts":false}
我正在邮递员中设置内容类型和授权

所有这些东西在postman中都可以完美地工作,但问题是,当我使用c#代码访问此端点时,代码不工作,请给出以下错误:-

我得到的错误是:-

{
  "id": "7b0ac743-58ea-4d61-a41d-a299f086a816",
  "timestamp": "2018-06-04T15:30:25.873Z",
  "lang": "en",
  "status": {
    "code": 400,
    "errorType": "bad_request",
    "errorDetails": "Invalid request content type, expecting \"multipart/form-data\" or \"application/json; charset\u003dutf-8."
  }
}
这是我的密码:

using ApiAi.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpClient http = new HttpClient();

            http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
            http.DefaultRequestHeaders.Add("ContentType", "application/json; charset=utf-8");
            http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxx");

            var response = http.PostAsync("https://api.dialogflow.com/v1/query?v=20150910", new StringContent(new Program().getSessionID(new ConfigModel { AccesTokenClient = "xxx" }, "flights from NYC to Vadodara"))).Result.Content.ReadAsStringAsync().Result;
        }
        public string getSessionID(ConfigModel config, string message)
        {
            var requestData = new RequestModel
            {
                query = message,
                sessionId = (config.SessionId ?? Guid.NewGuid()).ToString(),
                lang = "pt-BR"
            };
            return JsonConvert.SerializeObject(requestData);
        }
    }
    public class RequestModel
    {
        public string query { get; set; }
        public string sessionId { get; set; }
        public string lang { get; set; }
        public bool resetContexts { get; set; }
    }
}








//  
// Copyright (c) 2017 Nick Rimmer. All rights reserved.  
// Licensed under the MIT License. See LICENSE file in the project root for full license information.  
//

using ApiAi.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ApiAi.Models
{
    /// <summary>
    /// Services configuration
    /// </summary>
    public class ConfigModel
    {
        #region magic
        internal static string 
            BaseUrl = @"https://api.dialogflow.com/v1",
            VersionCode = @"20150910";

        #endregion

        /// <summary>
        /// Each API request requires authentication to identify the agent that is responsible for making the request. Authentication is provided through an access token.
        /// The developer access token is used for managing entities and intents.
        /// </summary>
        public string AccesTokenDeveloper { get; set; }

        /// <summary>
        /// Each API request requires authentication to identify the agent that is responsible for making the request. Authentication is provided through an access token.
        /// The client access token is used for making queries.
        /// </summary>
        public string AccesTokenClient { get; set; }

        /// <summary>
        /// Specifed language in your Api.ai agent
        /// </summary>
        public LanguagesEnum Language { get; set; }

        /// <summary>
        /// Timezone requests parameter
        /// </summary>
        public string TimeZone { get; set; } = System.TimeZone.CurrentTimeZone.StandardName;

        /// <summary>
        /// Session ID for request
        /// </summary>
        public object SessionId { get; set; } = Guid.NewGuid();
    }
}
使用apai.Models;
使用Newtonsoft.Json;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用System.Net.Http;
使用System.Net.Http.Header;
使用系统文本;
使用System.Threading.Tasks;
命名空间控制台应用程序6
{
班级计划
{
静态void Main(字符串[]参数)
{
HttpClient http=新的HttpClient();
http.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);//Accept标头
Add(“ContentType”,“application/json;charset=utf-8”);
http.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“承载者”、“xxx”);
var response=http.PostAsync(“https://api.dialogflow.com/v1/query?v=20150910,新StringContent(新程序().getSessionID(新配置模型{AccesTokenClient=“xxx”},“从纽约到瓦多达拉的航班”))).Result.Content.ReadAsStringAsync().Result;
}
公共字符串getSessionID(ConfigModel配置,字符串消息)
{
var requestData=新的RequestModel
{
查询=消息,
sessionId=(config.sessionId??Guid.NewGuid()).ToString(),
lang=“pt BR”
};
返回JsonConvert.SerializeObject(requestData);
}
}
公共类请求模型
{
公共字符串查询{get;set;}
公共字符串sessionId{get;set;}
公共字符串lang{get;set;}
公共布尔重置上下文{get;set;}
}
}
//  
//版权所有(c)2017年Nick Rimmer。版权所有。
//根据麻省理工学院许可证授权。有关完整的许可证信息,请参见项目根目录中的许可证文件。
//
使用apai.enum;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间apai.Models
{
/// 
///服务配置
/// 
公共类配置模型
{
#区域魔法
内部静态字符串
BaseUrl=@”https://api.dialogflow.com/v1",
VersionCode=@“20150910”;
#端区
/// 
///每个API请求都需要身份验证来标识负责发出请求的代理。身份验证通过访问令牌提供。
///开发者访问令牌用于管理实体和意图。
/// 
公共字符串AccesTokenDeveloper{get;set;}
/// 
///每个API请求都需要身份验证来标识负责发出请求的代理。身份验证通过访问令牌提供。
///客户端访问令牌用于进行查询。
/// 
公共字符串AccesTokenClient{get;set;}
/// 
///Api.ai代理中指定的语言
/// 
公共语言SENUM语言{get;set;}
/// 
///时区请求参数
/// 
公共字符串时区{get;set;}=System.TimeZone.CurrentTimeZone.StandardName;
/// 
///请求的会话ID
/// 
公共对象SessionId{get;set;}=Guid.NewGuid();
}
}
这是我正在使用的代码。 提前感谢。

本身有一个重载来设置内容类型:

var response = http.PostAsync(yourUrl, 
                              new StringContent("your json string",
                                                 Encoding.UTF8, "application/json"))
                   .Result.Content.ReadAsStringAsync().Result;
默认媒体类型设置为:
text/plain

Ps:您可能希望将它们拆分为更可读的函数。它有助于调试

文档在这一点上相当模糊,但正如您所看到的,
StringContent
有自己的
Headers
属性。我猜它将覆盖您的请求头

反编译程序集将显示mediatype的默认值,如您所见是
text/plain

/// <summary>Creates a new instance of the <see cref="T:System.Net.Http.StringContent" /> class.</summary>
/// <param name="content">The content used to initialize the <see cref="T:System.Net.Http.StringContent" />.</param>
[__DynamicallyInvokable]
public StringContent(string content)
  : this(content, (Encoding) null, (string) null)
{
}

/// <summary>Creates a new instance of the <see cref="T:System.Net.Http.StringContent" /> class.</summary>
/// <param name="content">The content used to initialize the <see cref="T:System.Net.Http.StringContent" />.</param>
/// <param name="encoding">The encoding to use for the content.</param>
/// <param name="mediaType">The media type to use for the content.</param>
[__DynamicallyInvokable]
public StringContent(string content, Encoding encoding, string mediaType)
  : base(StringContent.GetContentByteArray(content, encoding))
{
  this.Headers.ContentType = new MediaTypeHeaderValue(mediaType == null ? "text/plain" : mediaType)
  {
    CharSet = encoding == null ? HttpContent.DefaultStringEncoding.WebName : encoding.WebName
  };
}

非常感谢您,但您能解释一下为什么我需要传递这两个参数Encoding.UTF8,“application/json”是的,这是它的工作,但您能帮我澄清我的概念吗?很抱歉,由于声誉不好,我无法给出您的答案是的,好的。。。。好首先,我认为这不会有帮助,因为,正如你所说;您正在发送标题。尽管如此,我还是更新了答案。并且给了你一些分数,希望你能投XD。。。我想你可以把它标记为答案,但我需要再加4分才能提高你的答案,因为现在我的声誉是11,我需要15分才能提高答案。
//since utf-8 is the default.
http.DefaultRequestHeaders.Add("ContentType", "application/json");