c#aspx使用Ajax jquery调用检查会话
我使用Ajax jquery在服务器端调用c#webmethod:c#aspx使用Ajax jquery调用检查会话,c#,jquery,asp.net,ajax,C#,Jquery,Asp.net,Ajax,我使用Ajax jquery在服务器端调用c#webmethod: function AjaxPostCommon(config, callBack) { const request = $.ajax({ url: config.Url, type: "POST", data: config.Data, cache: false, contentType: "application/json; charset
function AjaxPostCommon(config, callBack) {
const request = $.ajax({
url: config.Url,
type: "POST",
data: config.Data,
cache: false,
contentType: "application/json; charset=utf-8",
beforeSend: config.BeforeSend,
statusCode: {
404: function () {
console.log("page not found");
}
}
})
.done(function (response) {
callBack(response);
})
.fail(function (xhr) {
console.log(config.Url + "\n" + xhr.statusText);
})
.always(config.Always);
return request;
}
和my.aspx.cs
class,一些函数如下:
[WebMethod]
public static dynamic HasTextures(StyleModel styleModel)
{
try
{
var userId = HttpContext.Current.Session["UserID"];
if (userId == null) return new { error = "-1" };
bool result = checkSomething();
return new { data = result };
}
catch (Exception e)
{
ExceptionHandler.LogException(e, GetUserId(), "PDC", "HasTextures");
return new { error = e.Message };
}
}
[WebMethod]
public static dynamic DeleteDesignFile(StyleModel styleModel)
{
try
{
var userId = HttpContext.Current.Session["UserID"];
if (userId == null) return new { error = "-1" };
return new { data = false };
}
catch (Exception e)
{
ExceptionHandler.LogException(e, GetUserId(), "PDC", "HasTextures");
return new { error = e.Message };
}
}
我正在检查会话,就像我在下面的代码中所做的一样。
我将在Jquery的回调中获取值。若错误=-1,我将重定向到登录页面。
有没有更好的方法来检查会话?并减少代码行数:
var userId = HttpContext.Current.Session["UserID"];
if (userId == null) return new { error = "-1" };
我考虑了属性
并做了研究。可以在此处应用吗?修改您的web.config以包括以下内容:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="index.aspx" />
</authentication>
<authorization>
<allow users="*"/>
</authorization>
如果用户未通过身份验证,上述操作将确保用户重定向到您的登录页面。然后在代码中,您可以使用HttpContext.Current.User.Identity.IsAuthenticated
检查用户是否经过身份验证 可能是@Hintham的复制品我看了一下。我想不出和那个问题有什么相似之处。对不起,你是对的,它没有完全涵盖你的问题。看到我的答案了吗