首先定义公共的返回对象
/// <summary> /// 返回数据对象 /// </summary> public class ResponseItem<T> { public Boolean success { get; set; } public String msg { get; set; } public T data { get; set; } public ResponseItem() { } public ResponseItem(Boolean success,String msg,T data) { this.success = success; this.msg = msg; this.data = data; } }
其次是所有的api接口都必须继承自ApiController。
文件上传的代码如下:
[HttpPost] public String SaveFile() { if (Request.Content.IsMimeMultipartContent()) { Request.Content.ReadAsMultipartAsync().ContinueWith(p => { foreach (var item in p.Result.Contents) { if (String.IsNullOrEmpty(item.Headers.ContentDisposition.FileName)) { continue; } item.ReadAsStreamAsync().ContinueWith(a => { Stream stream = a.Result; String fileName = item.Headers.ContentDisposition.FileName; fileName = fileName.Substring(1, fileName.Length - 2); //保存 byte[] r = new byte[stream.Length]; stream.Read(r, 0, r.Length); File.WriteAllBytes(Path.Combine("E:", fileName), r); }); } }); } return "1"; }
文件下载代码如下:
[HttpGet] public HttpResponseMessage DownLoadFile() { HttpResponseMessage result = null; result = new HttpResponseMessage(HttpStatusCode.OK); String fileName = HostingEnvironment.MapPath("~/packages.config"); FileStream fs = new FileStream(fileName, FileMode.Open); result.Content = new StreamContent(fs); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "MVC下载文件.txt"; return result; }
在Global.asax中配置全局的JSON日期格式化格式
//注册JSON序列化方式,设置日期格式 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings. Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } );
在Global.asax中配置全局的异常
//注册异常捕获类 GlobalConfiguration.Configuration.Filters.Add( new CustomerExceptionFilterAttribute() );
在webApiConfig中增加一个拦截器
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); //注册一个拦截器,所有请求都会经过这个拦截器 config.Filters.Add(new CusFilter());
拦截器代码如下:
namespace HelloWebAPI.Filter { public class CusFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { try { if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0) // 允许匿名访问 { base.OnActionExecuting(actionContext); return; } var cookie = actionContext.Request.Headers.GetCookies(); if (cookie == null || cookie.Count < 1) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden); return; } FormsAuthenticationTicket ticket = null; foreach (var perCookie in cookie[0].Cookies) { if (perCookie.Name == FormsAuthentication.FormsCookieName) { ticket = FormsAuthentication.Decrypt(perCookie.Value); break; } } if (ticket == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden); return; } // TODO: 添加其它验证方法 base.OnActionExecuting(actionContext); } catch { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden); } } } }
关于跨域允许访问的配置,需要修改web.config文件,如下:
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol>
东西比较凌乱,主要是记录一下方便以后查看!!!