备注:无论有没有安装 apb zero模块,都可以使用本文的跨域
首先配置Web Api:
1. 在Web API项目下,安装包
Install-Package Microsoft.AspNet.WebApi.Cors
2. 然后在 WebApiModule 的方法Initialize中,添加下面代码:(代码最好在ConfigureSwaggerUi的上面)
//设置跨域 var cors = new EnableCorsAttribute("*", "*", "*"); cors.SupportsCredentials = true; GlobalConfiguration.Configuration.EnableCors(cors);
上面配置了Web Api的跨域,然后我们想要在Web MVC中也支持跨域。下面我们给出登录模块支持跨域的例子。
然后配置Web MVC项目,让登录支持跨域:
1.我们创建一个Attribute类,叫做AcceessOriginalAttribute,如下:
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; namespace MagicQCes.Web.Filters { public class AcceessOriginalAttribute : ActionFilterAttribute, IExceptionFilter {public void InternalExuteAccessControle(HttpResponseBase response, HttpRequestBase request) { var header = response.Headers; var requestHeader = request.Headers; header.Set("Access-Control-Allow-Origin", requestHeader["Origin"] ?? "http://" + requestHeader["Host"]); header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); header.Set("Access-Control-Max-Age", "3600"); header.Set("Access-Control-Allow-Headers", "*"); header.Set("Access-Control-Allow-Credentials", "true"); } public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); } public override void OnActionExecuted(ActionExecutedContext filterContext) { InternalExuteAccessControle(filterContext.HttpContext.Response, filterContext.HttpContext.Request); base.OnActionExecuted(filterContext); } public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); } public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); } public void OnException(ExceptionContext filterContext) { filterContext.Result = new JsonResult() { Data = new { Succeed = 0, Message = filterContext.Exception.Message }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.ExceptionHandled = true; } } }
2.然后,我们在AccountController中,的Login方法中,添加上面属性,如下:
[AcceessOriginal] public async Task<JsonResult> Login(string usernameOrEmailAddress, string Password)
这样,登录也支持跨域了。
可以关注本人的公众号,多年经验的原创文章共享给大家。