1. 在 Global.asax.cs 文件中加入session支持
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } public override void Init() { //注册事件 this.AuthenticateRequest += WebApiApplication_AuthenticateRequest; base.Init(); } void WebApiApplication_AuthenticateRequest(object sender, EventArgs e) { //启用 webapi 支持session 会话 HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required); }
2.在 WebApiConfig.cs 中设置 路由session 传递
public static void Register(HttpConfiguration config) { RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ).RouteHandler = new SessionControllerRouteHandler(); } public class SessionRouteHandler : HttpControllerHandler, IRequiresSessionState { public SessionRouteHandler(RouteData routeData) : base(routeData) { } } public class SessionControllerRouteHandler : HttpControllerRouteHandler { protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { return new SessionRouteHandler(requestContext.RouteData); } }
3. 在web,config 中设置跨域配值
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Credentials" value="true" /> //设置 前端ip地址 <add name="Access-Control-Allow-Origin" value="http://localhost:8080" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol>
原文地址:https://www.cnblogs.com/zhuzy/p/9498144.html
时间: 2024-11-05 18:36:32