Javascript 使用JSON重定向到WebForm
我不想使用querystring将数据传递到重定向页面 当前实现,源页面:Javascript 使用JSON重定向到WebForm,javascript,jquery,asp.net,ajax,json,Javascript,Jquery,Asp.net,Ajax,Json,我不想使用querystring将数据传递到重定向页面 当前实现,源页面: window.location = "invaliduser.aspx?u=" + encodeURI(username); 我正在考虑使用AJAX方法,但不确定它是否会重定向到页面 登录页: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="invaliduser.aspx.cs" Inherits="iTask.Organizer.inval
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>
我们打算使用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
});
}
}
你是对的,你不能用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);
}
最后执行:
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):
无效用户
无效的用户帐户:
您的用户帐户()没有为此应用程序正确设置
如需进一步帮助,请联系
如果您需要助手函数的引用
GetJsonUTF8
,那么仅根据上面的用例示例转到,是什么驱动了“我不想使用查询字符串”?上面看起来“很好”,不确定您想要“获得”什么(?)…理想的情况是,我不想通过查询字符串将信息公然传递到页面。我知道任何有权查看网络的人都可以看到传递的数据,但我更希望URL看起来最小,而不是有一个附加了QueryString值列表的扩展URL。
/****
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";
});
....
}
<!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>