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>

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

  • 相关阅读:
    需求管理是CMM可重复级中的6个关键过程域之一,其主要目标是__________。A.客观地验证需求管理活动
    47、软件需求工程的活动可以划分为5个独立的阶段:需求获取、需求建模、形成需求规格、需求验证和需求管理,需求建模是()
    JavaScript alert()函数
    系统讲解一下,Dao,Entity,Servlet,Action各自有什么东西-Java/Web开发
    用Eclipse 开发Dynamic Web Project应用程序
    Connection conn = DriverManager.getConnection("jdbc:odbc:bbs");
    linux 常用快捷命令
    Docker 命令大全
    小白入门之十七:yum源配置并使用其安装软件包
    Linux从一般用户切换到root用户
  • 原文地址:https://www.cnblogs.com/duanjt/p/6420172.html
Copyright © 2011-2022 走看看