Web API session managment - asp.net

My requirements - I have a web api whch gives me all data from db. I have a .net website which consumes this api to get all data. Now what I want is when I'm login my website I want to manage session in "API".
I know session in web api is not a good approach but still I need to do this.
I have already implemented session management in web api(taken reference from here) and its working fine if I'm sending all my request from postman(i.e. I'm setting variables in session by calling 1 method and retrieving that session variable by calling 2nd method). But when I'm doing the same from asp.net website with jQuery then I'm not getting stored session variable(what I noticed is I'm getting session id different every time-for each request).
code of saving variable in session
$.ajax({
url: 'http://localhost:63726/api/Login/Login',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
code of retrieving variable stored in session
$.ajax({
url: 'http://localhost:63726/api/SessionCheck/LoginName',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
What I need to do to achieve my goal..Your opinion will save my days...

I found my answer Session management in web api.

Please, read this Web Api Session storage before.
To retreive data from session use javascript sessionStorage (instead ajax).

Related

How to call server api decorated with ValidateAntiForgeryToken using Httpclientfactory Typed clients?

I am trying to incorporate a Edit Form page using GetAsync and PostAsync using typed httpclient. Everything works except my code doesn't call API actions with ValidateAntiForgeryToken. Most of the examples online do not address httpcontent used by httpclientfactory and instead use httpresponse. I am aware that the antiforgery token is missing on my request. How do I attach it to the request header? How do I retrieve it from the view? I want to use as less Javascript as possible. Here's a snippet of my Post request service.
Edit: For what it's worth, my api is dot net core and client is dot net core mvc.
var response = await _httpclient.PostAsync("api/edit/" + id, httpcontent);
response.EnsureSuccessStatusCode(); ```
In the MVC Edit view page, it will use a hidden file (named __RequestVerificationToken) to store the ValidateAntiForgeryToken, you can use F12 developer tools to check it.
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">
After modifying the data, you could use JQuery to get the updated data, then use JQuery ajax to call the API method with the ValidateAntiForgeryToken. You can refer the sample code in my reply:
if we customize antiforgery options in Startup.ConfigureServices, such as: custom the Header Name for the RequestVerificationToken.
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); //configure the antiforgery service to look for the X-CSRF-TOKEN header. To prevent the cross-site request forgery.
Then, we could use the following script:
$.ajax({
type: "POST",
url: "/Survey/Create",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "CategoryName": $("#CategoryName").val(), "CategoryID": $("#CategoryID").val() },
success: function (response) {
alert(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Besides, you can also refer Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core.

Ajax call to ASP.NEt Web Api method. Parser error when it is done from HTTPS page

$.ajax({
url: "api/basket",
type: "GET",
dataType: "json",
error: function (request, status, error) {
alert(request.responseText);
},
success: function (data) {
Process(data);
}
});
I use ASP.NEN Web forms, .Net Framework 4.0, there is an ajax call above which I make . And when it is done from normal HTTP page it gives me data, But if I make this call being on HTTPS page it returns parserror "Unexpected token <"
What is wrong?
Your ajax request isn't returning JSON, it is returning HTML or XML. Thus, when jQuery attempts to parse the response, the first character is sees is < and it throws the parse error.
Use a debugging tool such as fiddler to see exactly what your request returns.

How do I do an AJAX post to a url within a class library but not the same IIS Web Application?

I have been working with ajax and there has been no problems below is how my ajax post code look like:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("TodoService.asmx/CreateNewToDo")%>',
data: jsonData,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function () {
//if (msg.d) {
$('#ContentPlaceHolder1_useridHiddenField').val("");
$('#ContentPlaceHolder1_titleTextBox').val("");
$('#ContentPlaceHolder1_destTextBox').val("");
$('#ContentPlaceHolder1_duedateTextBox').val("");
alert('Your todo has been saved');
// }
},
error: function (msg) {
alert('There was an error processing your request');
}
});
However, the problem came up when I try to get the url to a webservice that is located in a class library within the same solution.
This ASP.Net
says If you want to put the webservice in the classlibrary, you could try placing the Webservice.asmx.cs file in the class library and place the Webservice.asmx file in the web application project, and then using jquery to consume it in the .aspx page
If it's a different application than yours that's considered an XSS (Cross-site scripting) and it is not allowed.
You could however wrap the call to the external service in your own application (let's say in a REST service) and just call your service from jquery

Persisting Session State via multiple request using jQuery $.ajax()

just been trying to recieve the session value from multiple jquery ajax requests on the same domain name. i think i understand that each request is kind of a virtual browser request so the session is mutally exclusive to each request, but there must be a way some how, has anyone solved this. Basically this is what im trying to do:
I have tries using type: GET and POST but still no luck.
Can anyone help please, Thanks?
First request - Stores the product id in a session
$.ajax({
url: 'http://localhost/websitetest/test.aspx?storeproduct=' + productid,
type: 'GET',
async: true,
success: function(data) {
}
});
Second Request - From the callback variable "data" recieves the product id from the session
$.ajax({
url: 'http://localhost/websitetest/test.aspx,
type: 'GET',
async: true,
success: function(data) {
var productID = data;
}
});
There is no question to send ajax request while accessing Session variable from asp page.
Simply you can do is :
<%
String session_var = Session("name_of_session_variable");
%>
Even if you still want to try Ajax, I think you will need to print the session variable in test.aspx file using Response.Write(), which will automatically return the content.
Please check this for further reference.
Please correct me as well if I am wrong.
Thank you.

Session State not Retained over calls to a Page Method

My server side code:
[WebMethod(CacheDuration = 0, EnableSession = true)]
public static int UserID()
{
if (HttpContext.Current.Session["UserID"] == null) return 0;
int UserID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
return (UserID);
}
My Client side code:
$.ajax({
type: "POST", cache: false,
url: "Login.aspx/UserID",
data: "{'r':" + rnd() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
This codes runs well on my localhost.
and the "UserID" ajax call, return the right value of the Session parameter.
but when i try to upload my website on the server, the "UserID" ajax call always returns false!!
my server is asp.net 2.0 and I'm using jquery 1.3.2
So please help to solve this problem.
Read this article: ASP.NET Session State FAQ
I found my answer in this questions:
Q: Session states works on some web servers but not on others.
A: Maybe machine name problem. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112 .
Q: Why are my Session variables lost frequently when using InProc mode?
A: Probably because of application recycle. See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316148
Changing sessionState mode to "StateServer" solved the problem.
Use code below:
<sessionState mode="StateServer"
stateConnectionString="tcpip=localhost:42424"
cookieless="false"
timeout="999"/>
A few things to check :
Are you using WebFarm configuration? there might be a problem when using session in WebFarm configuration.
Have you check your network traffic using tools like Fiddler or FireBug? Is ASP.NET Auth cookie sent during AJAX call?
Can you confirm your session var is valid?

Resources