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">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、运行如下:
运行前:
运行后:
@H_403_0@ 总结以上是内存溢出为你收集整理的silverlight调用MVC WebApi方法全部内容,希望文章能够帮你解决silverlight调用MVC WebApi方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)