How to add header to HttpWebRequest in Windows8 ap

2019-02-10 06:48发布

问题:

I developing C#\XAML metro-ui application. I want to call some service and going to use HttpWebRequest for this. Previous realization of HttpWebRequest contains ContentLength and UserAgent properties. But realization for WinRT doesn't have it. I tried to use the approach described in this post. It works for UserAgent but not for ContentLength. I've tried to set Headers

request.Headers["Content-length"] = Length;
request.Headers["User-agent"] = UserAgent;

But received the exception "The 'Content-length' header must be modified using the appropriate property or method."

Hot is it possible to set Headers in HttpWebRequest realized in WinRT?

回答1:

HttpWebRequest has a semi-deprecated status under WinRT. Some header values that could previously be modified on earlier .NET platforms can no longer cannot be modified with it.

It seems that HttpClient is the new and improved replacement for HttpWebRequest with a simple API and full async support.

Since you want to specify Content-Length, I assume you're trying to POST or PUT something to the server. In that case, you will want to use PostAsync() or PutAsync() as appropriate.

    var req = new HttpClient();
    req.DefaultRequestHeaders.Add("User-agent", UserAgent);
    req.DefaultRequestHeaders.Add("Content-length", Length);
    return await req.PostAsync(RequestURL, Body);

You probably don't really need to specify the Content-length header, since it will be automatically included by those methods based on the actual length of the Body, but you can try it either way.