2015-08-27 28 views
0

我有一個用ASP.NET創建的Web應用程序和用C#編寫的Windows本地客戶端程序。
Windows本機程序需要從ASP.NET Web應用程序發送和提取數據。
我想在網絡應用程序中,我需要一個外部調用的控制器。而在客戶端軟件中,我需要打電話給他們。從C#(基於win32的)客戶端調用ASP.NET

  • 有沒有辦法用複雜的數據類型(類的列表)實現調用作爲參數?
  • 如何保護來自客戶端的呼叫?簡單的http登錄?

例如我想這個類的一個實例轉移到或從ASP.NET Web應用程序:

public class Address 
{ 
    public String Street {get;set;} 
    public String City {get;set;} 
} 
public class CustomerInformation 
{ 
public String No {get;set;} 
public String Name {get;set;} 
public List<Address> Addresses {get;set;} 
} 

當然Windows客戶端運行時,ASP.NET當地某處服務正在網絡上運行。

+0

您可以使用HttpClient的?如果是這樣,也許這會有所幫助? http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client – BattlFrog

回答

1

我會添加API控制器並在其中放置一些方法。例如

// Addresses API 
public class AddressController : ApiController 
{ 
    private readonly IRepository<Address> _repository; 

    public AddressController(IRepository<Address> repository) 
    { 
     _repository = repository; 
    } 

    [BasicAuthorize] 
    public IList<Address> GetList() 
    { 
     return _repository.GetAll(); 
    } 
} 

// Constomer information API 
public class CustomerInformationController : ApiController 
{ 
    private readonly IRepository<CustomerInformation> _repository; 

    public CustomerInformationController(IRepository<CustomerInformation> repository) 
    { 
     _repository = repository; 
    } 

    [BasicAuthorize] 
    public IList<CustomerInformation> GetList() 
    { 
     return _repository.GetAll(); 
    } 
} 

要保護這些方法,您可以使用基本身份驗證。這意味着您可以添加授權頭爲每個請求:

例如,它如何查找用戶「myuser的」帶密碼「測試」

授權:基本bXl1c2VyOnRlc3Q =

// Custom attribute for Basic authentication 
public class BasicAuthorizeAttribute : System.Web.Http.AuthorizeAttribute 
{ 
    private readonly string[] _permissionNames; 

    public BasicAuthorizeAttribute() 
    { 
    } 

    public BasicAuthorizeAttribute(params string[] permissionNames) 
    { 
     _permissionNames = permissionNames; 
    } 

    protected override bool IsAuthorized(HttpActionContext actionContext) 
    { 
     // check if user has been already authorized 
     if (base.IsAuthorized(actionContext)) 
      return true; 

     var user = AuthenticateUser(actionContext); 

     // here you can check roles and permissions 

     return user != null; 
    } 

    private IUser AuthenticateUser(HttpActionContext context) 
    { 
     var request = context.Request; 
     AuthenticationHeaderValue authHeader = request.Headers.Authorization; 
     if (authHeader != null) 
     { 
      // RFC 2617 sec 1.2, "scheme" name is case-insensitive 
      if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authHeader.Parameter != null) 
       return AuthenticateUser(authHeader.Parameter); 
     } 
     return null; 
    } 

    private IUser AuthenticateUser(string credentials) 
    { 
     try 
     { 
      // parse values 
      var encoding = Encoding.GetEncoding("iso-8859-1"); 
      credentials = encoding.GetString(Convert.FromBase64String(credentials)); 

      var credentialsArray = credentials.Split(':'); 
      var username = credentialsArray[0]; 
      var password = credentialsArray[1]; 

      // authentication 
      var membershipService = new IMembershipService(); 
      return membershipService.ValidateUser(username, password); 
     } 
     catch (Exception) 
     { 
      // Credentials were not formatted correctly. 
      return null; 
     } 
    } 
} 

在客戶端可以使用的HttpClient發送異步請求

public async Task<Address[]> GetAddresses() { 
     var client = new HttpClient {BaseAddress = new Uri(_settingsService.GetHost())}; 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

     var base64 = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "myuser", "test"))); 
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",base64); 

     HttpResponseMessage response = await client.GetAsync("api/addresses"); 
     if (response.StatusCode != HttpStatusCode.OK) 
      throw new Exception(response.ReasonPhrase); 

     string content = await response.Content.ReadAsStringAsync(); 
     return JsonConvert.DeserializeObject<Address[]>(content); 
    } 
+0

這看起來不錯 - 我該如何發送數據到服務? – Sam

+0

發現它:當然PostAsync。謝謝! – Sam

0

有沒有辦法用複雜的數據類型(類的列表)來實現調用作爲參數?

是的,服務器應用程序作爲ASP.NET或ASP.NET MVC或(最好)ASP.NET WEB API可以提供具有複雜數據類型的服務。實際上,聲明方法沒有限制。

如何保護來自客戶端的呼叫?簡單的http登錄?

有在ASP.NET(MVC,WEB API),它給你機會選擇一個他們的認證和授權機制的廣泛ranage。

通過XML或JSON在客戶端和服務器之間傳輸數據。

「WebClient」類提供了從客戶端到服務器進行呼叫所需的一切。

的更多信息: