1、创建ASP.NET MVC4 Web应用程序,选择WebAPI模板
2、添加silverlight项目
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NetMVCAPI.Models { public class Contact { int Id { get; set; } string Name { set; } string Gender { set; } } }
using System.Net;
using System.Net.Http;
using System.Web.Http;
using NetMVCAPI.Models;
namespace NetMVCAPI.Controllers
{
class ContactController : ApiController
{
Contact[] contacts = new Contact[]
{
new Contact(){ Id=1,Name="mk",Gender=男"},2,0); line-height:1.5!important">ll3,0); line-height:1.5!important">hj4,0); line-height:1.5!important">zxm女5,0); line-height:1.5!important">wmq/// <summary>
/// /api/Contact
</summary>
<returns></returns>
public IEnumerable<Contact> GetListAll()
{
return contacts;
}
/api/Contact/id
<param name="id"></param>
public Contact GetContactById(int id)
{
Contact contact = contacts.FirstOrDefault<Contact>(item => item.Id == id);
if (contact == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return contact;
}
根据性别查询
/api/Contact?Gender=女
<param name="gender"></param>
public IEnumerable<Contact> GetListByGender(string gender)
{
return contacts.Where(item => item.Gender == gender);
}
根据姓名查询
/api/Contact/Name=mk
<param name="name"></param>
public IEnumerable<Contact> GetListByName(string name)
{
return contacts.Where(item => item.Name == name);
}
}
}
5、通过silverlight访问WebApi
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
{
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(try
{
TextBlock_Result.Text = e.Result;
}
catch (Exception ex)
{
TextBlock_Result.Text = ex.Message;
}
}
}
}
6、运行如下:
运行前:
运行后:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。