我有一种情况,我不想使用查询字符串将数据传递到重定向页面。
当前实施,源页面:
window.location = "invaliduser.aspx?u=" + encodeURI(username);
我正在考虑使用AJAX方法,但不确定它是否会重定向到页面。
登陆页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="invaliduser.aspx.cs" Inherits="iTask.Organizer.invaliduser" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Invalid User</title>
<script type="text/javascript" src="Scripts/jquery-2.1.0.js"></script>
<script src="Scripts/app.utility.js"></script>
<script src="Scripts/InvalidUser.js"></script>
</head>
<body>
<h1>Invalid User Account:</h1>
<p>Your user account ( <span id="pUserName"></span> ) is not properly setup for this application.</p>
<p>Please contact the <a href="mailto:email@domain.com">Email recipient</a> for further assistance.</p>
</body>
</html>
当前的JQuery:
jQuery(function ($) {
$(document).ready(function () {
var username = decodeURI(getUrlVars().u);
$("#pUserName").text(username);
});
});
是不是要使用AJAX POST方法将JSON数据传递给页面,但不确定它是否会继续往返,因为我需要将数据传递给页面(不使用QueryString),理想情况下所有都在同一个请求,因此重定向与JSON数据打包在一起。
理论AJAX / JSON帖子:
PostJsonUTF8(
'invaliduser.aspx',
{ data: username },
function (resp) {
window.location = "invaliduser.aspx";
}
);
function PostJsonUTF8(url, data, success) {
PostAPI('json', 'application/json;charset=utf-8', url, data, success);
}
function PostAPI(type, contentType, url, data, success) {
if (typeof (success) === 'function') {
$.ajax({
type: "POST",
contentType: contentType,
dataType: type,
url: url,
data: data,
success: success,
error: AjaxFail
});
}
}
答案 0 :(得分:1)
你是对的,你不能用AJAX做正常的重定向(301/302状态代码)。我通常做的是在我的AJAX响应处理逻辑中设置以下内容:
function tryHandleResponseRedirect(resp, data) {
if (resp.status == 200 && data && data.redirect) {
// force a hard re-direct
window.location.href = data.redirect;
return true;
}
}
您可以使用jQuery的ajaxSuccess
函数:
$( document ).ajaxSuccess(function( event, xhr, settings, data ) {
tryHandleResponseRedirect(xhr, data);
});
然后我在服务器端执行以下操作,我可以处理所有传出的HTTP响应:
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var req = filterContext.HttpContext.Request;
var resp = filterContext.HttpContext.Response;
var shouldProcess = (resp.IsRequestBeingRedirected && req.IsAjaxRequest());
if (!shouldProcess)
{
base.OnResultExecuted(filterContext);
return;
}
var location = resp.RedirectLocation ?? resp.Headers["location"];
var json = JsonConvert.SerializeObject(new { redirect = location });
resp.ClearContent();
resp.Headers.Remove("location");
// send back a JSON object indicating a redirect
resp.StatusCode = 200;
resp.Write(json);
}
答案 1 :(得分:0)
最终实施: ApiController:
[RoutePrefix( "api/users" )]
public class UsersController : ApiController {
//GET api/users/netid
[HttpGet , Route( "get/netid" )]
public HttpResponseMessage GetUserId () {
using ( var ctx = new DbContext() ) {
JavaScriptSerializer s = new JavaScriptSerializer();
var username = RequestContext.Principal.Identity.Name;
try {
var userid = ctx.Get_User_Id( username ).SingleOrDefault();
if ( userid == default( string ) ) {
return this.BadRequestResponse( s.Serialize( new { username=username } ) );
} else {
return this.OKResponse( s.Serialize( userid ) );
}
} catch ( Exception ex ) {
return this.InternalServerResponse( ex );
}
}
}
}
使用Javascript:
/****
Return a well formatted API URL for Users
---------------------------------------------
~/api/users/get/netid
****/
function ApiGetUsersUrl() {
return 'api/users/get/netid';
}
$(document).ready(function(){
....
GetJsonUTF8(
ApiGetUsersUrl(),
function (resp) { //Success Function
userid = JSON.parse(resp);
//Cache Common Templates
//Load Team DropDownList
LoadTeamDropDownList();
},
null,
function (xhr, status, err) { //Error Function
console.log(JSON.parse(xhr.responseJSON).username);
window.location = "invaliduser.aspx";
});
....
}
Html / Aspx页面(invaliduser.aspx):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Invalid User</title>
</head>
<body>
<h1>Invalid User Account:</h1>
<p>Your user account ( <%=Request.LogonUserIdentity.Name %> ) is not properly setup for this application.</p>
<p>Please contact the <a href="mailto:user@domain.com">User Name</a> for further assistance.</p>
</body>
</html>
如果您需要帮助函数GetJsonUTF8
的参考,请转到The IT Hobbit - JQuery/Ajax Helper