赞
踩
什么是webservice?
webservice是一个平台独立的、低耦合的、自包含的、基于可编程的Web应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准来描述、发布、发现、协调和配置这些应用程序,用于开发分布式的互操作的应用程序。
Webservice技术能使得运行在不同机器上的不同应用无须借助附加的、专门的第三方软件或硬件就可相互交换数据或集成。
创建一个WebService并调用
public class MyWebService : System.Web.Services.WebService
{
/// <summary>
/// 乘法运算
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
[WebMethod(Description = "乘法运算(计算两个数相乘的结果)")]
public int Multiplier(int a, int b)
{
return a * b;
}
}
http://localhost:20914/MyWebService.asmx 调用地址
如果想要别人也能访问到,我们需要把这个Web服务发布到IIS上面。选中MyWebService.asmx 在浏览器中查看。
在项目中添加引用:
选中项目添加新项-web窗体,命名为webform1。Webform1.aspx页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebAppService.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtA" runat="server"></asp:TextBox> *<asp:TextBox ID="txtB" runat="server"></asp:TextBox> <asp:Button ID="btnGetResult" runat="server" Text="=" OnClick="btnGetResult_Click" /><asp:TextBox ID="txtResult" runat="server"></asp:TextBox> </div> </form> </body> </html> 在这里插入代码片
webform1后台代码:
在using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebAppService { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnGetResult_Click(object sender, EventArgs e) { ServiceRef.MyWebServiceSoapClient _client = new ServiceRef.MyWebServiceSoapClient(); txtResult.Text = _client.Multiplier(int.Parse(txtA.Text.Trim()), int.Parse(txtB.Text.Trim())).ToString(); } } }这里插入代码片
运行项目:
为了方便统一把web服务寄宿在IIS上,项目中我们一般会把所有web服务放到一个为web站点,发布到IIS上共用户调用。
WebApi可以返回Json、Xml类型的数据,对于数据的增删改查提供对应的资源操作,按照请求的类型进行相应的处理。,主要包括Get(查),Post(增),Put(改)、Delete(删),这些都是Http协议支持的请求方式。
创建WebApi
新建项目Web-ASP.NET MVC 应用程序。命名位WebApiApp,在项目模板中选中Web Api。
在Models类中新建类Product。
在using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApiApp.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
新建Api控制器Products,右击目录Controllers,添加控制器。和普通控制不一样,这里要继承ApiController。如图:
using System.Collections.Generic; using System.Linq; using System.Web.Http; using WebApiApp.Models; namespace WebApiApp.Controllers { public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerable<Product> GetAllProducts() { return products; } public Product GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); return product; } } }
调用WebApi:
有两种调用方式
1.JQuery Ajax (可以网上去查)
2.HttpClient(第二种重点)
新建MVC项目WebApiClient
ModelS文件下创建Product类 添加程序集引用WepApi达到公用。
添加Home控制器和Index的Action方法。
using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Mvc; using WebApiClient.Models; namespace WebApiClient.Controllers { public class HomeController : Controller { public ActionResult Index() { //客户端对象的创建与初始化 HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //执行Get操作 HttpResponseMessage response = client.GetAsync("http://localhost:16947/api/Products").Result; var list = response.Content.ReadAsAsync<List<Product>>().Result; ViewData.Model = list; return View(); } } }
index界面:
在这里插@{
ViewBag.Title = "Index";
}
@model List<WebApiClient.Models.Product>
<ul>
@foreach (var v in Model)
{
<li>@v.Id","@v.Name,@v.Price</li>
}
</ul>入代码片
注意一点更要先云翔WebApiApp,在云香WebApiClient.
WebApi 授权:
只对指定给客户开户。开发中比较常用也是难点。类似于授权验证。
新建过滤器类APIAuthorizeAttribute在WebApiApp项目中filter文件下:
在这using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Web.Http.Filters; namespace WebApiApp.Filter { public class APIAuthorizeAttribute : AuthorizationFilterAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { //如果用户使用了forms authentication,就不必在做basic authentication了 if (Thread.CurrentPrincipal.Identity.IsAuthenticated) { return; } var authHeader = actionContext.Request.Headers.Authorization; if (authHeader != null) { if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && !String.IsNullOrWhiteSpace(authHeader.Parameter)) { var credArray = GetCredentials(authHeader); var userName = credArray[0]; var key = credArray[1]; string ip = System.Web.HttpContext.Current.Request.UserHostAddress; } } HandleUnauthorizedRequest(actionContext); } private string[] GetCredentials(System.Net.Http.Headers.AuthenticationHeaderValue authHeader) { //Base 64 encoded string var rawCred = authHeader.Parameter; var encoding = Encoding.GetEncoding("iso-8859-1"); var cred = encoding.GetString(Convert.FromBase64String(rawCred)); var credArray = cred.Split(':'); return credArray; } private bool IsResourceOwner(string userName, System.Web.Http.Controllers.HttpActionContext actionContext) { var routeData = actionContext.Request.GetRouteData(); var resourceUserName = routeData.Values["userName"] as string; if (resourceUserName == userName) { return true; } return false; } private void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='eLearning' location='http://localhost:8323/APITest'"); } } }
把这个过滤器添加到全局过滤器中,不要添加到filterconfig.cs中(仅MVC用),而是webApiconfig.cs(webapi用)。App_start文件下:
using System.Collections.Generic; using System.Linq; using System.Web.Http; using WebApiApp.Filter; namespace WebApiApp { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Filters.Add(new APIAuthorizeAttribute()); //添加授权验证过滤器 } } }
WebApi调试
个人用PostMan调试,其余方式可以自己百度 (偷个懒,哈哈!) 写了两天。
天色不早了 ,毕竟快一点了 ,明天继续最后的WCF,这个比较复杂点 ,大家晚安!
处女作首秀,工作了块两年多C#程序员,说来有点惭愧,一直主要做业余偏多,忽视很多重要的知识点,自己加强,给自己定一个计划,每周至少一个博客,以后也尽力在git上开源一下小项目,督促自己成长。不在迷茫,更进一步!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。