首页 > 解决方案 > DataServiceContext.ExecuteAsync 导致有关 User-Agent 标头的异常

问题描述

我创建了一个 Xamarin.Forms 应用程序并添加了一个连接的 Odata 服务。现在,当我尝试向后端发送请求时,它将失败并出现异常 System.ArgumentException: The 'User-Agent' header must be modified using the appropriate property or method。参数名称:名称。

我试过的:

1:处理 DataServiceContext_BuildingRequest 并使用 e.Headers["User-Agent"] = "xyz";

2:设置 Content-Type 标头,因为我在另一个线程中读到它有帮助的地方(e.Headers.Add("Content-Type", "application/json"))

3:设置DataServiceContext.Configurations.RequestPipeline.OnMessageCreating的委托。问题是,一旦我尝试创建一个新的 HttpWebRequestMessage 实例并传入它接收到的参数,就会抛出异常。

管道代表:

Configurations.RequestPipeline.OnMessageCreating = (args) =>
{
    args.Headers["User-Agent"] = "xyz";                
    args.Headers.Add("Content-Type", "application/json");
    args.Headers["Accept"] = "application/json";
    var req = new HttpWebRequestMessage(args);
    req.HttpWebRequest.ContentType = "application/json";
    return req;
};

我对此的怀疑是,Odata HttpWebRequestMessage 类使用的底层代码发生了一些变化,不再允许直接设置 User-Agent 标头。

有没有人找到解决这个问题的方法?

标签: xamarin.formsodataodata-connected-service

解决方案


推荐阅读