c# - Web 请求内容类型总是 text/html

标签 c# json asp.net-mvc httpwebrequest webrequest

我有一个网络 API 需要使用。 此 api 将根据我发送的内容类型返回数据。 通常它会返回 html 响应。 如果请求具有带有“application/json” header 的 Content-Type header ,它将返回一个 json 响应。

当我尝试使用 Postman 并添加内容类型 header (如 application/json)时,一切都很好。 但是当使用 C# WebRequest 对象尝试它时,无论我使用的是什么内容类型 header ,我总是得到 html 响应。 我用fiddler看web请求,content type一直是text/html。

这是我的代码。 试过这个:

    var webAddr = "https://xxxxxxxx.com/api/blabla";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.Method = "GET";

        httpWebRequest.Headers.Add("Authorization", "Basic xxxxxxxxxxx==");
        httpWebRequest.ContentType = "application/json; charset=utf-8";

        HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();


        Stream resStream = response.GetResponseStream();
        using (var reader = new StreamReader(resStream))
        {
            result = reader.ReadToEnd();
        }
        txtResult.Text = result;

也试过这个:

var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

        request.Method = Method.ToString();
        request.ContentLength = 0;
        request.ContentType = "application/json";

            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
            request.Headers.Add("Authorization", "Basic " + encoded);



        using (var response = (HttpWebResponse)request.GetResponse())
        {
            var responseValue = string.Empty;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                return null;
            }

            // grab the response
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseValue = reader.ReadToEnd();
                    }
            }

仍然,每次内容类型都是文本/html。

提前致谢, 沙乌尔

最佳答案

您要做的是设置Accept header ,而不是Content-TypeAccept 指定您要接收的数据类型。 Content-Type 用于指定您发送的数据类型。

httpWebRequest.Accept = "application/json";

关于c# - Web 请求内容类型总是 text/html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803815/

相关文章:

perl - 用perl解析json

asp.net-mvc - ASP.NET MVC : IAuthorizationFilter/Attribute prefered security check for login?

c# - Unity DI 帐户 Controller 中的 IRepositories 为空

C# 转换接口(interface)

c# - Visual Studio 2010 自动附加到进程

c# - 处理大型位图(最大 3GB)

c# - 控制其他

c# - C#中如何交叉连接反序列化json数据

json - Meteor.http.call(调用URL API)

c# - 使用 IronPython 扩展 ASP.Net MVC 网站