2013-12-16 20 views
17

Tôi gặp sự cố khi gọi tới điểm kết thúc WCF webHttpBinding bằng cách sử dụng HttpClient và thuộc tính BaseAddress.HttpClient với BaseAddress

HttpClient

Tôi tạo ra một trường hợp HttpClient xác định tài sản như một thiết bị đầu cuối máy chủ địa phương BaseAddress.

enter image description here

GetAsync Gọi

Sau đó tôi gọi GetAsync phương pháp đi qua trong inforamtion Uri bổ sung.

HttpResponseMessage response = await client.GetAsync(string.Format("/Layouts/{0}", machineInformation.LocalMachineName())); 

enter image description here

endpoint Dịch vụ

[OperationContract] 
[WebGet(UriTemplate = "/Layouts/{machineAssetName}", ResponseFormat = WebMessageFormat.Json)] 
List<LayoutsDto> GetLayouts(string machineAssetName); 

Vấn đề

Vấn đề tôi đang gặp là là /AndonService.svc phần của BaseAddress đã được cắt ngắn nên cuộc gọi kết quả đi đến https://localhost:44302/Layouts/1100-00277 thay vì https://localhost:44302/AndonService.svc/Layouts/1100-00277 dẫn đến 404 Không tìm thấy.

Có lý do nào để BaseAddress bị cắt bớt trong cuộc gọi GetAsync không? Làm thế nào để tôi có được điều này?

+0

thể trùng lặp của [? Tại sao HttpClient BaseAddress không làm việc] (http://stackoverflow.com/questions/23438416/why-is-httpclient-baseaddress- không hoạt động) –

Trả lời

40

Trong BaseAddress, chỉ cần bao gồm dấu gạch chéo cuối cùng: https://localhost:44302/AndonService.svc/. Nếu không, phần cuối cùng của đường dẫn sẽ bị hủy bỏ, vì nó không được coi là "thư mục".

này mẫu mã minh họa sự khác biệt:

// No final slash 
var baseUri = new Uri("https://localhost:44302/AndonService.svc"); 
var uri = new Uri(baseUri, "Layouts/1100-00277"); 
Console.WriteLine(uri); 
// Prints "https://localhost:44302/Layouts/1100-00277" 


// With final slash 
var baseUri = new Uri("https://localhost:44302/AndonService.svc/"); 
var uri = new Uri(baseUri, "Layouts/1100-00277"); 
Console.WriteLine(uri); 
// Prints "https://localhost:44302/AndonService.svc/Layouts/1100-00277" 
+0

Cảm ơn bạn đã hiểu. Sửa lỗi đơn giản –

+2

Vui lòng xem câu hỏi và câu trả lời của tôi ở đây: http://stackoverflow.com/questions/23438416/why-is-httpclient-baseaddress-not-working Câu trả lời này để lại một chi tiết quan trọng. –

Các vấn đề liên quan