错误必须使用适当的属性或方法修改'Accept'标头。参数名称:名称

时间:2018-12-29 13:06:29

标签: c# asp.net json.net http-headers httpwebrequest

访问开放​​端点(HMRC开发人员网站的Hello World API)时遇到问题。

如果没有server_token或OAuth 2.0 access_token,则此端点不受限制。提供的步骤是:

  1. //向发出GET请求 https://test-api.service.hmrc.gov.uk/hello/world

  2. //为他们的Hello World端点构造GET请求

    HttpClient客户端= HttpClientBuilder.create()。build(); HttpGet request = new HttpGet(“ https://test-api.service.hmrc.gov.uk/hello/world”); request.addHeader(“ Accept”,“ application / vnd.hmrc.1.0 + json”);

  3. //执行请求

HttpResponse响应= client.execute(request);

  1. //提取HTTP状态代码和响应正文 int statusCode = response.getStatusLine()。getStatusCode(); 字符串responseBody = EntityUtils.toString(response.getEntity());

我现在尝试按以下步骤在C#中复制这些步骤:

public string RequestHeaders()
{   
        try
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://test-api.service.hmrc.gov.uk/hello/world");

            request.Method = "GET";
            request.ContentType = @"application/vnd.hmrc.1.0+json";
            request.Headers.Add("Accept", @"application/vnd.hmrc.1.0+json");
            request.Accept = @"application/vnd.hmrc.1.0+json";
            request.KeepAlive = true;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }
                }
                else
                    return response.StatusCode.ToString() + "</br>" + response.StatusDescription;

            }
        }
        catch (WebException errMsg)
        {
            return "Error Status Code : " + ((HttpWebResponse)errMsg.Response).StatusCode + "</br>" +
              ((HttpWebResponse)errMsg.Response).StatusDescription;

        }
        catch (Exception errMsg)
        {
            return errMsg.Message + errMsg.StackTrace;
        }
}

我得到了错误:

必须使用适当的属性或方法来修改“ Accept”标头。参数名称:c .:第33行中System.Net.WebHeaderCollection.ThrowOnRestrictedHeader(String headerName)的名称在System.Net.WebHeaderCollection.Add(String name,String value)的RequestHeaders()处

第33行:是

request.Accept = @“ application / vnd.hmrc.1.0 + json”;

我也尝试过变体:

// request.Headers.Add(header,headerValue);
//request.Headers[HttpRequestHeader.Accept] =标头;

我尝试过:

https://test-api.service.hmrc.gov.uk/hello/world?Accept=application/vnd.hmrc.1.0+json

并获取相应的内联错误消息为

{“代码”:“ ACCEPT_HEADER_INVALID”,“消息”:“接受标头丢失或无效”}

如何修复标头上的parameter:name并按API预期返回“ Hello World”。

似乎我缺少了一些非常简单的内容...

0 个答案:

没有答案