zoukankan      html  css  js  c++  java
  • webapi研究说明

    首先定义公共的返回对象

    /// <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";
    }
    View Code

    文件下载代码如下:

    [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;
    }
    View Code

    在Global.asax中配置全局的JSON日期格式化格式

    //注册JSON序列化方式,设置日期格式
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.
        Converters.Add(new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
        }
    );
    View Code

    在Global.asax中配置全局的异常

    //注册异常捕获类
    GlobalConfiguration.Configuration.Filters.Add(
        new CustomerExceptionFilterAttribute()
    );
    View Code

    在webApiConfig中增加一个拦截器

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    
    //注册一个拦截器,所有请求都会经过这个拦截器
    config.Filters.Add(new CusFilter());
    View Code

    拦截器代码如下:

    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);
                }
            }
        }
    }
    View Code

    关于跨域允许访问的配置,需要修改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>

     东西比较凌乱,主要是记录一下方便以后查看!!!

  • 相关阅读:
    Win8系统 Python安装
    一些安卓开源框架整理
    Android 媒体键监听以及模拟媒体键盘的实现 demo
    android View 自动 GONE 问题
    Android 定时器TimerTask 简单使用
    关于Android studio 相对 eclipse 优点
    Java序列化与反序列化
    android shape的使用 边框
    Android Studio 修改 包名 package name
    Android WebView Long Press长按保存图片到手机
  • 原文地址:https://www.cnblogs.com/duanjt/p/6420172.html
Copyright © 2011-2022 走看看