I have Ajax jquery to call c# webmethod in server-side:
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;
}
and my.aspx.cs
class, some functions like these:
[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 };
}
}
I'm checking session like what I did in code below.
I'll get value in callBack
of Jquery. If error = -1, I will redirect to Login page.
Are there a better way to check session? and reduce lines of code:
var userId = HttpContext.Current.Session["UserID"];
if (userId == null) return new { error = "-1" };
I thought about Attribute
and did research. Can apply here?