我正在使用uploadify来批量上传文件,我收到302重定向错误。我假设这是因为在脚本调用中没有传回一些asp.net身份验证cookie令牌。
我已经在一个普通的裸机mvc3应用程序中工作但是当我尝试将其集成到一个安全的asp.net mvc3应用程序中时,它会尝试重定向到account / signin。
我有一个身份验证令牌(@auth),它在视图中作为长字符串返回,但我仍然得到302重定向错误。
有关如何发送Cookie身份验证数据的任何想法?
查看:
@{
string auth = @Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
}
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function () {
jQuery("#bulkupload").uploadify({
'uploader': '@Url.Content("~/Scripts/uploadify.swf")',
'cancelImg': '/Content/themes/base/images/cancel.png',
'buttonText': 'Browse Files',
'script': '/Creative/Upload/',
scriptData: { token: "@auth" },
'folder': '/uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'sizeLimit': '38000',
'multi': true,
'auto': true,
'onError' : function (event,ID,fileObj,errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
});
</script>
控制器:
public class CreativeController : Controller
{
public string Upload(HttpPostedFileBase fileData, string token)
{
...
}
}
更新:好的,这适用于IE9但不适用于Chrome(Chrome会抛出302)。 FF甚至没有渲染控件。
有人知道如何在最新的转速中使用它 Chrome和FF?
答案 0 :(得分:5)
当我尝试将uploadify与asp.net mvc3一起使用时,我遇到了类似的问题。经过大量的谷歌搜索,这是我发现似乎工作。它主要涉及声明自定义属性,然后将身份验证cookie显式传递到Uploadify的HTTP Post并通过自定义属性手动处理cookie。
首先声明此自定义属性:
/// <summary>
/// A custom version of the <see cref="AuthorizeAttribute"/> that supports working
/// around a cookie/session bug in Flash.
/// </summary>
/// <remarks>
/// Details of the bug and workaround can be found on this blog:
/// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class TokenizedAuthorizeAttribute : AuthorizeAttribute
{
/// <summary>
/// The key to the authentication token that should be submitted somewhere in the request.
/// </summary>
private const string TOKEN_KEY = "authCookie";
/// <summary>
/// This changes the behavior of AuthorizeCore so that it will only authorize
/// users if a valid token is submitted with the request.
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string token = httpContext.Request.Params[TOKEN_KEY];
if (token != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
if (ticket != null)
{
var identity = new FormsIdentity(ticket);
string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
var principal = new GenericPrincipal(identity, roles);
httpContext.User = principal;
}
}
return base.AuthorizeCore(httpContext);
}
}
然后声明此Action将身份验证cookie传递给ViewData,以便将其传递给Uploadify小部件。这也是您稍后调用以实例化Uploadify小部件的操作。
[Authorize]
public ActionResult UploadifyUploadPartial()
{
ViewBag.AuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName] == null
? string.Empty
: Request.Cookies[FormsAuthentication.FormsCookieName].Value;
return PartialView("UploadifyUpload");
}
这是UploadifyUpload View的代码。它基本上是设置Uploadify的JavaScript的包装器。我没有修改就复制了我,所以你必须根据你的应用进行调整。需要注意的重要一点是,您要通过UploadifyUploadPartial Action中的ViewData将authCookie
传递到scriptData
属性。
@if (false)
{
<script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
}
@{
ViewBag.Title = "Uploadify";
}
<script src="@Url.Content("~/Scripts/plugins/uploadify/swfobject.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/plugins/uploadify/jquery.uploadify.v2.1.4.min.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Scripts/plugins/uploadify/uploadify.css")" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
CreateUploadifyInstance("dir-0");
});
function CreateUploadifyInstance(destDirId) {
var uploader = "@Url.Content("~/Scripts/plugins/uploadify/uploadify.swf")";
var cancelImg = "@Url.Content("~/Scripts/plugins/uploadify/cancel.png")";
var uploadScript = "@Url.Content("~/Upload/UploadifyUpload")";
var authCookie = "@ViewBag.AuthCookie";
$('#uploadifyHiddenDummy').after('<div id="uploadifyFileUpload"></div>');
$("#uploadifyFileUpload").uploadify({
'uploader': uploader,
'cancelImg': cancelImg,
'displayData': 'percentage',
'buttonText': 'Select Session...',
'script': uploadScript,
'folder': '/uploads',
'fileDesc': 'SunEye Session Files',
'fileExt': '*.son2',
'scriptData' : {'destDirId':destDirId, 'authCookie': authCookie},
'multi': false,
'auto': true,
'onCancel': function(event, ID, fileObj, data) {
//alert('The upload of ' + ID + ' has been canceled!');
},
'onError': function(event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
},
'onAllComplete': function(event, data) {
$("#treeHost").jstree("refresh");
//alert(data.filesUploaded + ' ' + data.errors);
},
'onComplete': function(event, ID, fileObj, response, data) {
alert(ID + " " + response);
}
});
}
function DestroyUploadifyInstance() {
$("#uploadifyFileUpload").unbind("uploadifySelect");
swfobject.removeSWF('uploadifyFileUploadUploader');
$('#uploadifyFileUploadQueue').remove();
$('#uploadifyFileUploadUploader').remove();
$('#uploadifyFileUpload').remove();
}
</script>
<div id="uploadifyHiddenDummy" style="visibility:hidden"></div>
<div id="uploadifyFileUpload">
</div>
对于上传帖子的操作,请使用新的TokenizedAuthorize
属性,而不是Authorize
属性:
[HttpPost]
[TokenizedAuthorize]
public string UploadifyUpload(HttpPostedFileBase fileData)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Form["authCookie"]);
if (ticket != null)
{
var identity = new FormsIdentity(ticket);
if (!identity.IsAuthenticated)
{
return "Not Authenticated";
}
}
// Now parse fileData...
}
最后,要使用我们编写的代码,请在您希望托管Uploadify小部件的任何View上通过Html.Action Helper调用UploadifyUploadPartial Action:
@Html.Action("UploadifyUploadPartial", "YourUploadControllerName")
此时你应该好好去。该代码应该适用于FF,Chrome和IE 9.如果您遇到问题,请告诉我。