c# - WebView - 在每个请求上定义 User-Agent

标签 c# webview httprequest win-universal-app windows-10-universal

目前我正在设置请求消息的User-Agent如下:

var rm = new HttpRequestMessage(HttpMethod.Post, new Uri("http://example.com"));       
rm.Headers.Add("User-Agent", "UserAgentString");
webView.NavigateWithHttpRequestMessage(rm);

一切都按预期进行。

但是,当我导航到另一个页面时,例如通过单击站点上的链接,用户代理将重置为 WebView 的默认值。

是否有任何方法可以永久设置用户代理或根据每个请求更改它?

谢谢, 乔治

最佳答案

我找到了 this trick by Matt Dot .这将永久更改用户代理字符串。任何 WebView 请求,无论是手动请求还是通过 HTML 中的链接单击,都会将您的值作为 User-Agent header 发送。

如果链接失效,这里是源。

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 ;)");

    // ...
}

关于c# - WebView - 在每个请求上定义 User-Agent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856266/

相关文章:

c# - Application.StartupPath 在 Windows CE 中的等效项是什么?

c# - 向按钮控件添加自定义属性 C#

javascript - 网页是否有可能检测到它是从 webview 应用程序访问的?

android - 如何在加载 WebView 页面时为警告对话框设置不同的标题?

php - iPhone OS 图像/照片大小调整工具可更改 EXIF 方向数据

javascript - 使用 CloudCode 在 Parse.com 中保存来自 URL 的图像

c# - 具有多次插入的存储过程 SQL 和 ASP.Net

c# - 在类属性上使用 JsonConverter 时选择 NamingStrategy

c#/asp.net - 如何捕获 "System.Web.HttpException: Request timed out"?

unit-testing - 如何使用 grails 测试单个文件上传 Controller (没有 content-type= multipart/form-data)