I found 马特·多特的这个技巧 http://gist.github.com/mattdot/3b53af7756c061e06f60623c766f657a。这将永久更改用户代理字符串。任何WebView
请求,无论是手动请求还是通过 HTML 内的链接单击,都会将您的值作为 User-Agent 标头发送。
这是链接失效时的来源。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace UA
{
public static class UserAgent
{
const int URLMON_OPTION_USERAGENT = 0x10000001;
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkGetSessionOption(int dwOption, StringBuilder pBuffer, int dwBufferLength, ref int pdwBufferLength, int dwReserved);
public static string GetUserAgent()
{
int capacity = 255;
var buf = new StringBuilder(capacity);
int length = 0;
UrlMkGetSessionOption(URLMON_OPTION_USERAGENT, buf, capacity, ref length, 0);
return buf.ToString();
}
public static void SetUserAgent(string agent)
{
var hr = UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, agent, agent.Length, 0);
var ex = Marshal.GetExceptionForHR(hr);
if(null != ex)
{
throw ex;
}
}
public static void AppendUserAgent(string suffix)
{
SetUserAgent(GetUserAgent() + suffix);
}
}
}
您可以在应用程序中的任何位置更改此值,但如果您希望永久设置它,请使用App.xaml.cs
构造函数:
public App()
{
UA.UserAgent.SetUserAgent("Firefox ;)");
// ...
}