关于WebAPI的跨域解决方案
1.引入包 Microsoft.AspNet.WebApi.Cors
2.在WebApiConfig中添加如下代码,建议使用域名来代替*
1 var cors = new EnableCorsAttribute("*", "*", "*"); 2 config.EnableCors(cors);
WebUpload上传图片
1 <div class="am-g am-margin-top am-margin-left"> 2 <div class=" am-u-sm-4 am-u-md-2 am-text-center title">行动轨迹<span class="asterisk">*</span></div> 3 <div class="am-u-sm-4 am-u-md-5 am-text-left" id="uploader_gj"> 4 5 <button id="ctlBtn" class="am-btn am-btn-primary am-btn-sm"> 6 <i class="am-icon-cloud-upload"></i> 请选择</button> 7 8 </div> 9 10 <div class="am-u-sm-4 am-u-md-5 am-text-left"> 11 <a class="am-badge am-badge-success am-round" id="gj_tips" style="display: none;" >√</a> 12 </div> 13 14 </div>
1 var uploaderGj = WebUploader.create({ 2 // 选完文件后,是否自动上传。 3 auto: true, 4 // 文件接收服务端。 5 server: GetUrl('SaveImage'),//'http://localhost:59246/api/Home/SaveImage', 6 //选择器 7 pick: { 8 id:'#uploader_gj', 9 multiple:false, 10 }, 11 12 accept: { 13 title: 'Images', 14 extensions: 'gif,jpg,jpeg,bmp,png', 15 mimeTypes: 'image/*' 16 }, 17 //可重复上传 18 duplicate :true, 19 });
如果在上传之前需要做些验证或者动态传入参数的话,可以参考如下做法
1 //文件上传之前触发 2 uploaderGj.on( 'beforeFileQueued', function( file ) { 3 4 var userid= $('#gtk_userid').val(); 5 if(isEmpty(userid)) 6 { 7 PopUpTips('请您先输入工号','#dd514c'); 8 $('#modalloading').modal('close'); 9 return false; 10 } 11 else { 12 var formData={ 13 UserID:GetUserId(), 14 BacthDir:GetBartch(), 15 DestDir:'GuiJi' 16 }; 17 uploaderGj.option('formData', formData); 18 19 return true; 20 } 21 22 }); 23
做到这里你以为大功告成了嘛,年轻人,你太天真了,在你上传图片的时候,会给你报跨域的错误,具体错误内容就不展示了,告诉解决方案:WebUpload在上传文件之前,会先发送一个OPTIONS请求,来验证你是否跨域。既然知道了原因,那我就在webApi上一个处理机制
1 在webconfig文件下添加下面的配置 2 <system.webServer> 3 <modules> 4 <add name="SpecialMethodModule" type="EpidemicPreventionPlatform.SpecialMethodModule" /> 5 </modules> 6 </system.webServer>
添加处理类
1 using System; 2 using System.Web; 3 4 namespace EpidemicPreventionPlatform 5 { 6 public class SpecialMethodModule : IHttpModule 7 { 8 public SpecialMethodModule() { } 9 public void Init(HttpApplication app) 10 { 11 app.BeginRequest += new EventHandler(this.BeginRequest); 12 } 13 public void Dispose() { } 14 public void BeginRequest(object resource, EventArgs e) 15 { 16 HttpApplication app = resource as HttpApplication; 17 HttpContext context = app.Context; 18 if (context.Request.HttpMethod.ToUpper() == "OPTIONS") 19 { 20 context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); 21 context.Response.StatusCode = 200; 22 context.Response.End(); 23 } 24 } 25 } 26 27 }