在mvc3中使用uploadify上传组件User.isAuthenticated等于false解决方法
我们前台html这样定义
@{ var auth = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value; } <script src="@Url.Content("~/Uploadify/swfobject.js")" type="text/javascript"></script> <script src="@Url.Content("~/Uploadify/jquery.uploadify.v2.1.4.min.js")" type="text/javascript"></script> <script type="text/javascript"> // <![CDATA[ $(document).ready(function () { $('#file_upload').uploadify({ 'uploader': '@Url.Content("~/Uploadify/uploadify.swf")', 'script': '@Url.Content("~/Admin/Product/Process")', 'cancelImg': '@Url.Content("~/uploadify/cancel.png")', 'folder': '@Url.Content("~/Content/goods")', // 'scriptData': { 'ASPSESSID':@sessionId' }, 'auto': true, 'multi': true, 'queueID': 'custom-queue', 'fileExt': '*.jpg;*.gif;*.png', 'fileDesc': 'Image Files (.JPG, .GIF, .PNG)', 'queueSizeLimit': 10, 'onSelectOnce': function (event, data) { $('#file_upload').uploadifySettings('scriptData', {'token': '@auth' }); $('#status-message').text(data.filesSelected + ' files have been added to the queue.'); }, 'onAllComplete': function (event, data) { $('#status-message').text(data.filesUploaded + ' files uploaded, ' + data.errors + ' errors.'); } }); }); // ]]>
注意这句
$('#file_upload').uploadifySettings('scriptData', {'token': '@auth' });
选择文件的时候,我们把auth也返回到服务器上.注意这里参数名"token"
然后我们后台:
public class UploadAuthenticationAttribute : AuthorizeAttribute { private const string TOKEN_KEY = "token"; protected override bool AuthorizeCore(HttpContextBase httpContext) { string token = httpContext.Request.Params[TOKEN_KEY]; if (token != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token); if (ticket != null) { FormsIdentity identity = new FormsIdentity(ticket); string[] roles = {"Administrators" }; //System.Web.Security.Roles.GetRolesForUser(identity.Name); 注意这里,如果你没有启用asp.net权限系统,会报错。 GenericPrincipal principal = new GenericPrincipal(identity, roles); httpContext.User = principal; } } return base.AuthorizeCore(httpContext); }
在你要上传的action上面加个[UploadAuthentication]就行了。
例如:
[UploadAuthentication] public void Process(HttpPostedFileBase fileData, string folder) { //dosomething... }