当我点击谷歌对话框流程的终点时,在c#中获取错误,但是同一个谷歌对话框流端点正在邮递员

时间:2018-06-04 15:50:28

标签: c# postman

我在PostMan中使用此端点: -

https://api.dialogflow.com/v1/query?v=20150910

我发送的这个JSON字符串: -

{"query":"flights from NYC to Vadodara","sessionId":"6b9d4676-2a71-4c64-a562-8c08f198c623","lang":"pt-BR","resetContexts":false}

我正在邮递员中设置内容类型和授权。

所有这些东西都完全适用于邮递员,但问题是当我使用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();
    }
}

这是我正在使用的代码。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

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

var response = http.PostAsync(yourUrl, 
                              new StringContent("your json string",
                                                 Encoding.UTF8, "application/json"))
                   .Result.Content.ReadAsStringAsync().Result;

默认媒体类型设置为:text/plain

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

这个文档非常模糊,但正如您所见hereStringContent拥有自己的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
  };
}

PS:你也可以尝试:

//since utf-8 is the default.
http.DefaultRequestHeaders.Add("ContentType", "application/json");