Skip to main content
 首页 » 编程设计

c#之Xamarin 上的 WebHeaderCollection 和 HttpWebRequest

2024年01月24日25lyhabc

我正在尝试将我的项目从 Mac 上的 Xamarin Studio 移植到 Windows 7 上的 Visual Studio 2012。 在 Mac 和 XS 上一切正常。在 VisualStudio 2012 上,我遇到了这两个问题:

Error 3 'System.Net.WebHeaderCollection' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Net.WebHeaderCollection' could be found (are you missing a using directive or an assembly reference?) C:\Users\user\Documents\Visual Studio 2012\Projects\MyProject\MyProject.Core\Services\MyProjectService.cs

Error 4 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?) C:\Users\user\Documents\Visual Studio 2012\Projects\MyProject\MyProject.Core\Services\MyProjectService.cs

在该代码上:

    var request = WebRequest.Create("https://www.myaddress.com/test/") as HttpWebRequest; 
    request.Method = "GET"; 
    request.Accept = "application/json"; 
    request.Headers.Add(HttpRequestHeader.Cookie,"mycookievalue"); 
 
    // Get response   
    using (var response = request.GetResponse() as HttpWebResponse) 
    { 
        // Get the response stream   
        var reader = new StreamReader(response.GetResponseStream()); 
        content = reader.ReadToEnd(); 
    } 

我该如何解决?

请您参考如下方法:

到目前为止,您提到的事情没有实现。 但没关系。他们仍然做得很好!

回答您的问题。

错误 3。是的。目前您只能使用 Headers["key"] = value。但。不是每个标题。我试图将“Content-Length”放在那里(因为也没有实现“ContentLength”属性),但出现“restricted headers”异常。 然而,请求 POST 为我成功处理,所以我放弃了。

错误 4。是的。没有这样的方法。 (同样的方式,因为没有“GetRequestStream”(例如,如果您要将 POST 数据写入请求流))。好消息是分别有 BeginGetResponse 和 BeginGetRequestStream,并且 C# action methods 简化了所有厨房。

(另外,我敢肯定,这对于异步实践的一般理解非常有用)。

可以在 Microsoft official docs 上找到基本示例.

但是我使用了以下操作来完成它:

    public void MakeRequest(string url, string verb, Dictionary<string, string> requestParams, 
        Action<string> onSuccess, Action<Exception> onError) 
    { 
        string paramsFormatted; 
 
        if (verb == "GET") 
        { 
            paramsFormatted = string.Join("&", requestParams.Select(x => x.Key + "=" + Uri.EscapeDataString(x.Value))); 
            url = url + (string.IsNullOrEmpty(paramsFormatted) ? "" : "?" + paramsFormatted); 
        } 
        else 
        { 
            // I don't escape parameters here, 
            // as Uri.EscapeDataString would throw exception if the parameter length 
            // is too long, so you must control that manually before passing them here 
            // for instance to convert to base64 safely 
            paramsFormatted = string.Join("&", requestParams.Select(x => x.Key + "=" + (x.Value))); 
        } 
 
        var request = (HttpWebRequest)WebRequest.Create(url); 
        request.Method = verb; 
 
        requestParams = requestParams ?? new Dictionary<string, string>(); 
 
        Action goRequest = () => MakeRequest(request,  
            response => 
            { 
                onSuccess(response); 
            }, 
            error => 
            { 
                if (onError != null) 
                { 
                    onError(error); 
                } 
            }); 
 
        if (request.Method == "POST") 
        { 
            request.BeginGetRequestStream(ar => 
            { 
                using (Stream postStream = request.EndGetRequestStream(ar)) 
                { 
                    byte[] byteArray = Encoding.UTF8.GetBytes(paramsFormatted); 
                    postStream.Write(byteArray, 0, paramsFormatted.Length); 
                } 
                goRequest(); 
            }, request); 
        } 
        else // GET 
        { 
            goRequest(); 
        } 
    } 
 
    private void MakeRequest(HttpWebRequest request, Action<string> onSuccess, Action<Exception> onError) 
    { 
        request.BeginGetResponse(token => 
        { 
            try 
            { 
                using (var response = request.EndGetResponse(token)) 
                { 
                    using (var stream = response.GetResponseStream()) 
                    { 
                        var reader = new StreamReader(stream); 
                        onSuccess(reader.ReadToEnd()); 
                    } 
                } 
            } 
            catch (WebException ex) 
            { 
                onError(ex); 
            } 
        }, null); 
    }