1.新建項目 > 選擇 web 應用程式 選擇 webApi 2. 創建一個httpmodeule類 放到app_data文件夾下 public class MyHttpModule : IHttpModule { #region IHttpModule 成員 public void Dispose ...
1.新建項目 ---> 選擇 web 應用程式 選擇 webApi 2. 創建一個httpmodeule類 放到app_data文件夾下
public class MyHttpModule : IHttpModule { #region IHttpModule 成員 public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; string url = context.Request.FilePath; string json = string.Empty; try { if (url.Contains("/api/"))//只要訪問路徑是介面的都要驗證token { } } catch { json = "{\"resultCode\": \"0\",\"data\":{\"returnInfo\":\"伺服器異常\"}}"; context.Response.Write(json); context.Response.End(); } } #endregion }2.在app strat 文件夾下麵 WebApiConfig 修改成如下代碼
public static void Register(HttpConfiguration config) { // Web API 路由 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); var appjsonType = config.Formatters.JsonFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "text/json"); config.Formatters.JsonFormatter.SupportedMediaTypes.Remove(appjsonType); }3.項目管理nuget包 AttributeRouting 搜索 安裝如下nuget包 AttributeRouting (ASP.NET Web API) 選擇安裝 4.接下來在webconfig中配置文件
在<system.web> 節點下麵 配置
<httpModules> <add name="項目名稱.MyHttpModule" type="項目名稱.MyHttpModule" /> </httpModules>
在 <system.webServer>節點西面配置 添加如下內容
<validation validateIntegratedModeConfiguration="false" /> <modules> <add name="項目名稱.MyHttpModule" type="項目名稱.MyHttpModule" /> </modules> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> <add name="AttributeRouting" path="routes.axd" verb="*" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" /> </handlers> <directoryBrowse enabled="true" />
好了 寫到這裡 程式 就OK 了 高手輕噴