ASP.NET Web API

出自ProgWiki
跳至導覽 跳至搜尋

ASP.NET Web API

  • 是ASP.NET 4.0以後新增的技術,必需放在ASP.NET MVC的網站內使用

技術文件

FAQ

讓Web API支援Session存取

  • 檔案: App_Start\WebApiConfig.cs
using System;
using System.Web.Http;
using System.Web.SessionState;
using System.Web.Http.WebHost;
using System.Web.Routing;
using System.Web;
 
namespace MvcApp1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            RouteTable.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
 
            ).RouteHandler = new SessionRouteHandler();
        }
    }
 
    public class SessionControllerHandler : HttpControllerHandler, IRequiresSessionState
    {
        public SessionControllerHandler(RouteData routeData)
            : base(routeData)
        { }
    }
 
 
    public class SessionRouteHandler : IRouteHandler
    {
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            return new SessionControllerHandler(requestContext.RouteData);
        }
    }
}
  • 使用時用 System.Web.HttpContext.Current.Session["變數名稱"]
或是 System.Web.SessionState.HttpSessionState Session = System.Web.HttpContext.Current.Session;

例外處理

ApiController不支援回傳Json?

  • WebAPI 第1版無解, 請改用ASP.NET MVC的 Controller
  • WebAPI2, ApiController已內建支援 Json

WebAPI與帳號驗證機制