- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 .NET 中的 HttpClient 来使用 Web 服务,并且在我完成了 msdn 中提到的所有步骤之后
o 出现以下异常:提供了无效的请求 URI。请求 URI 必须是绝对 URI,或者必须设置 BaseAddress。
这是我的类(class)
public class Customer
{
public int id { get; set; }
public string id_default_group { get; set; }
public string id_lang { get; set; }
public string newsletter_date_add { get; set; }
public string ip_registration_newsletter { get; set; }
public string last_passwd_gen { get; set; }
public string secure_key { get; set; }
public string deleted { get; set; }
public string passwd { get; set; }
public string lastname { get; set; }
public string firstname { get; set; }
public string email { get; set; }
public string id_gender { get; set; }
public string birthday { get; set; }
public string newsletter { get; set; }
public string optin { get; set; }
public string website { get; set; }
public string company { get; set; }
public string siret { get; set; }
public string ape { get; set; }
public string outstanding_allow_amount { get; set; }
public string show_public_prices { get; set; }
public string id_risk { get; set; }
public string max_payment_days { get; set; }
public string active { get; set; }
public string note { get; set; }
public string is_guest { get; set; }
public string id_shop { get; set; }
public string id_shop_group { get; set; }
public string date_add { get; set; }
public string date_upd { get; set; }
public string reset_password_token { get; set; }
public string reset_password_validity { get; set; }
}
class Program
{
static void ShowProduct(Customer customer)
{
Console.WriteLine($"Email: {customer.email}\tFirst Name: {customer.firstname}");
}
static async Task<Uri> CreateCustomerAsync(Customer customer)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync("api/customers/1?output_format=JSON", customer);
response.EnsureSuccessStatusCode();
// return URI of the created resource.
return response.Headers.Location;
}
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
NetworkCredential hd = new NetworkCredential("INHFTLZLMLP1TUTJE7JL9LETCCEW63FN", "");
HttpClientHandler handler = new HttpClientHandler {Credentials = hd };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:8080/newprestashop/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
Customer customer = new Customer();
var url = await CreateCustomerAsync(customer);
// Get the product
customer = await GetProductAsync(url.PathAndQuery);
ShowProduct(customer);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
static async Task<Customer> GetProductAsync(string path)
{
Customer customer = null;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
customer = await response.Content.ReadAsAsync<Customer>();
}
return customer;
}
}
}
最佳答案
BaseAddress 在那里,因此您可以进行与 BaseAddress 相关的所有调用。它有效,您只需要了解 BaseAddress Why is HttpClient BaseAddress not working? 的一些特性即可
但是您的问题是您在每个方法中都实例化了一个新的 HttpClient。
static async Task<Uri> CreateCustomerAsync(Customer customer)
{
HttpClient client = new HttpClient();
//you never set the BaseAddress
//or the authentication information
//before making a call to a relative url!
HttpResponseMessage response = await client.PostAsJsonAsync("api/customers/1?output_format=JSON", customer);
response.EnsureSuccessStatusCode();
// return URI of the created resource.
return response.Headers.Location;
}
更好的方法是将 HttpClient 调用包装在一个类中,并将其放在构造函数中,然后在您的任何方法中共享它
public WrapperClass(Uri url, string username, string password, string proxyUrl = "")
{
if (url == null)
// ReSharper disable once UseNameofExpression
throw new ArgumentNullException("url");
if (string.IsNullOrWhiteSpace(username))
// ReSharper disable once UseNameofExpression
throw new ArgumentNullException("username");
if (string.IsNullOrWhiteSpace(password))
// ReSharper disable once UseNameofExpression
throw new ArgumentNullException("password");
//or set your credentials in the HttpClientHandler
var authenticationHeaderValue = new AuthenticationHeaderValue("Basic",
// ReSharper disable once UseStringInterpolation
Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password))));
_httpClient = string.IsNullOrWhiteSpace(proxyUrl)
? new HttpClient
{
DefaultRequestHeaders = { Authorization = authenticationHeaderValue },
BaseAddress = url
}
: new HttpClient(new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Address = new Uri(proxyUrl),
BypassProxyOnLocal = false,
UseDefaultCredentials = true
}
})
{
DefaultRequestHeaders = { Authorization = authenticationHeaderValue },
BaseAddress = url
};
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.AcceptEncoding.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<Member> SomeCallToHttpClient(string organizationId)
{
var task = await _httpClient.GetStringAsync(<your relative url>));
return JsonConvert.DeserializeObject<SomeType>(task,
new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()});
}
关于c# - 提供了无效的请求 URI。请求 URI 必须是绝对 URI,或者必须设置 BaseAddress。尝试使用网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43809746/
我正在使用 .NET 4 框架创建一个 C# 库项目(这是 Visual Studio 2012 中现有解决方案中的一个新项目)。我看到一些较旧的现有项目正在项目属性中指定 DLL 的 BaseAdd
从我所见,在IIS中托管WCF服务时,将忽略该标记。我知道在进行自我托管时这是必需的,但是在IIS下运行时是否有害甚至使用? 例如
我是 WCF 的新手,我从一个简单的无文件应用程序部分(web.config)开始我的体验,您可以在下面看到: 现在我
IHttpClientFactory 和更改 HttpClient.BaseAddress 的最佳实践是什么? 在创建我的依赖注入(inject)时,我这样做是这样的: services.AddHtt
所以我们大多数人可能已经读到我们应该重用 HttpClient 的实例,而不是使用 using 并创建新实例。这意味着我可以在我的程序中创建一个 HttpClient 的实例,并在每个请求中使用完整的
我在调用 webHttpBinding 时遇到问题WCF 端点使用 HttpClient和 BaseAddress属性(property)。 HttpClient 我创建了一个 HttpClient指
考虑以下代码,其中 BaseAddress 定义了部分 URI 路径。 using (var handler = new HttpClientHandler()) using (var client
在本例中,Hosting Blazor ,作者有一个调用 Azure Functions 的 Blazor ClientSide App。作者设置了一个Http.BaseAddress。关于在以下情况
我创建了一个服务,但没有在 servicehost 构造函数中提供基地址。并通过调用 AddServiceEndpoint 方法将端点添加到主机。在 AddServiceEndpoint 方法中,我提
我们在项目中使用HttpClient 调用多个域的多个API。我正在创建一个通用的 HttpClient 以用于所有这些 API 调用。我对实现这个的两种方法感到困惑: 为 HttpClient 创建
我们有一个包含许多 dll 文件的项目,这些文件在应用程序启动时加载。 dll 文件的基地址确实重叠,因此内存镜像被重新定位。是否有可能自动分配基地址或为每个 dll 文件计算“好”基地址的方法? 最
我有一个包含几个 WCF 服务的程序集,每个服务都有自己的契约(Contract)。这一切都很好。该服务的 app.config 中的服务配置如下所示:
在我的 App.config 中,我指定了这个基地址(“jerrycan”是我计算机的名称):
在 MSDN 中我找到以下内容` BaseAddress - 指向页面区域基地址的指针。 AllocationBase - 指向由 VirtualAlloc 函数分配的页面范围的基地址的指针。 Bas
我正在尝试实现“Win32 EXE 的动态 fork ”的已知方法,它被称为 RunPE。我的问题是我无法获得在 http://www.security.org.sg/code/loadexe.htm
据此 https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.baseaddress(v=vs.118).aspx 它包
据此 https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.baseaddress(v=vs.118).aspx 它包
我正在尝试部署一个 WCF 服务,但我很难让最后的部分发挥作用。我不是部署大师,所以请多多包涵。 我正在使用 WebHttpBinding 对使用 JSON 的服务进行 Ajax 调用,但我收到错误:
在 Silverlight 应用程序中,我有时需要连接到托管该应用程序的网站。为了避免在我的 Silverlight 应用程序中对网站进行硬编码,我使用如下代码: WebClient webClien
我正在尝试使用 .NET 中的 HttpClient 来使用 Web 服务,并且在我完成了 msdn 中提到的所有步骤之后 o 出现以下异常:提供了无效的请求 URI。请求 URI 必须是绝对 URI
我是一名优秀的程序员,十分优秀!