webapi研究說明

首先定義公共的返回對象web

/// <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。api

文件上傳的代碼以下:跨域

[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

文件下載代碼以下:cookie

[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日期格式化格式app

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

在Global.asax中配置全局的異常ide

//註冊異常捕獲類
GlobalConfiguration.Configuration.Filters.Add(
    new CustomerExceptionFilterAttribute()
);
View Code

在webApiConfig中增長一個攔截器this

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

//註冊一個攔截器,全部請求都會通過這個攔截器
config.Filters.Add(new CusFilter());
View Code

攔截器代碼以下:spa

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文件,以下:3d

<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>

 東西比較凌亂,主要是記錄一下方便之後查看!!!code

相關文章
相關標籤/搜索