微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

silverlight调用MVC WebApi方法

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
    {
        int Id { get; set; }

        string Name { set; }


        string Gender { set; }
    }
}

复制代码

 

4、新建一个控制器,代码如下:

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">zxm5,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] 举报,一经查实,本站将立刻删除。

相关推荐