1、創建ASP.NET MVC4 Web應用程序,選擇WebAPI模板
2、添加silverlight項目
3、新建一個數據模型類,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NetMVCAPI.Models { public class Contact { public int Id { get; set; } public string Name { get; set; } public string Gender { get; set; } } }
4、新建一個控制器,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using NetMVCAPI.Models; namespace NetMVCAPI.Controllers { public class ContactController : ApiController { Contact[] contacts = new Contact[] { new Contact(){ Id=1, Name="mk", Gender="男"}, new Contact(){ Id=2, Name="ll", Gender="男"}, new Contact(){ Id=3, Name="hj", Gender="男"}, new Contact(){ Id=4, Name="zxm", Gender="女"}, new Contact(){ Id=5, Name="wmq", Gender="女"}, }; /// <summary> /// /api/Contact /// </summary> /// <returns></returns> public IEnumerable<Contact> GetListAll() { return contacts; } /// <summary> /// /api/Contact/id /// </summary> /// <param name="id"></param> /// <returns></returns> public Contact GetContactById(int id) { Contact contact = contacts.FirstOrDefault<Contact>(item => item.Id == id); if (contact == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return contact; } /// <summary> /// 根據性別查詢 /// /api/Contact?Gender=女 /// </summary> /// <param name="gender"></param> /// <returns></returns> public IEnumerable<Contact> GetListByGender(string gender) { return contacts.Where(item => item.Gender == gender); } /// <summary> /// 根據姓名查詢 /// /api/Contact/Name=mk /// </summary> /// <param name="name"></param> /// <returns></returns> public IEnumerable<Contact> GetListByName(string name) { return contacts.Where(item => item.Name == name); } } }
5、通過silverlight訪問WebApi
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SilverlightApplication1 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { var uriStr = new Uri(Application.Current.Host.Source, TextBoxUri.Text); var wc = new WebClient(); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringAsyncCompleted); wc.DownloadStringAsync(uriStr); } void DownloadStringAsyncCompleted(object sender, DownloadStringCompletedEventArgs e) { try { TextBlock_Result.Text = e.Result; } catch (Exception ex) { TextBlock_Result.Text = ex.Message; } } } }
6、運行如下:
運行前:
運行后: