i have a web method that check user in data base via a jquery-ajax method i wanna if client exists in db i create a cookie in client side with user name but i know that response is not available in staticmethod .how can i create a cookie in a method that call with jquery ajax and must be static. its my code that does not work cuz response is not accesible
if (olduser.Trim() == username.Trim() && password.Trim()==oldpass.Trim())
{ retval =olduser;
HttpContext context = HttpContext.Current;
context.Session[retval.ToString()] = retval.ToString();
HttpCookie cook = new HttpCookie("userath");
cook["submituser"] = "undifiend";
Response.Cookies.Add(cook);
}
You can access the Response object in the same way you are accessing the Session object from the current HtppContext.
Your code should end like this:
context.Response.Cookies.Add(cook);
You could pass the HttpContext into the static method from the Web Method that the AJax call first enters.
EDIT: or, don't use a static method. Either way, the HttpContext will be available from the instanced Web Method that the Ajax call sees via [WebMethod] annotation.
First make an ajax call. You can read this great tutorial 5 Ways to Make Ajax Calls with jQuery
Second get the server respond. For example if the callback was '1', it means you should set the cookie and if it was '0' you should not.
At Last you can easily set the cookie using this jquery plugin: jquery.cookie.
Related
I am having difficulty to understand some code from GitHub (I am learning angular, however this is server side code written in c#)
The code is available on GitHub code).
I can't completely understand the very first line of code var refreshToken = Request.Cookies["refreshToken"]; Where does Request.Cookies come from? It is not a variable and it looks like a static call to some array Cookies. How does the element of that array happen to contain "refresh-token" item?
Could someone please explain this? (this code comes from the class derived from BaseController)
[HttpPost("refresh-token")]
public ActionResult<AuthenticateResponse> RefreshToken()
{
var refreshToken = Request.Cookies["refreshToken"];
var response = _accountService.RefreshToken(refreshToken, ipAddress());
setTokenCookie(response.RefreshToken);
return Ok(response);
}
When you work in an HTTP application, .NET manages some context for you. A bunch of stuff you write, like your POST action, is provided with an HTTP context, which has properties that provide information about the request. This includes headers, cookies, etc.
When you use Request within an MVC controller (or some other HTTP context) you'll get access to the HttpContext and Request that relates to the specific single request. It feels like magic, but it's the framework doing the work for you.
A bit more information on context.
You need to check other serverside codes which set the cookie,Cookie is created in serverside firstly and sent to User Agent,often stored in your browser.next time you send a request,your request may contain the cookie
you could check the codes like:Response.Cookies.Append(....)
I am using a WebAPI service in my webapplication. In this service is used for all account functions (/api/account/login, /api/account/logout, ...). Within the same webroot I have a website which uses this webAPI service to communicate with the backend system. So from my C# code i'm calling the IsLoggedIn function in my WebAPI which returns true when I'm logged in. This is working great.
[HttpGet]
public bool IsLoggedIn()
{
return (WebSecurity.IsAuthenticated);
}
In my arearegistration i added the following code:
context.Routes.MapHttpRoute("Account", "api/account/{action}/{id}", new { Controller = "Account", id = RouteParameter.Optional });
And the follwing GlobalConfiguration:
GlobalConfiguration.Configuration.Filters.Add(new ExceptionHandlingAttribute());
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
The custom ExceptionHandlingAttribute checks if the thrown exception is of a specific type and returns a custom ReasonPhrase, so nothing special.
When I'm logged in and call the function from javascript (jQuery) or in Fiddler the IsLoggedIn function returns false. What should I add to my jQuery call to make sure the the right user is still found in the WebAPI? This is happening for POST and GET calls.
Please help :)
It will always be false as REST is stateless, each request knows nothing about previous requests.
You could enable Session State by doing something like this
http://www.strathweb.com/2012/11/adding-session-support-to-asp-net-web-api/
A better approach would be to have your Login call return a token which is then passed on subsequent calls to identify the user. Here's an example:
How to use OAuth 2 - OAuth 2 C# example
I have web service with 40 different web methods.
Can I get in my web service the Method that the request sent from using HttpContext?
I need it because I have abstract general command that all the methods activate and I have access only to HttpContext.
Thanks!
If I understand correct your question you can use PathInfo property of the HttpRequest:
string methodName = HttpContext.Current.Request.PathInfo;
The string methodName will be the method name with the slash prefix (/): "/MyWebMethod".
You probably need:
HttpContext.Current
But be sure you've the ASPX compatibility mode turned on, otherwise you'll not be able to access that property
You can also save the name of the function into the Items array like this:
void myServiceMethod()
{
HttpContext.Current.Items["MethodName"] = "myServiceMethod";
// ...
// here comes your method implementation
}
and then you can anywhere read the HttpContext.Current.Items["MethodName"]
colection HttpContext.Current.Items is valid always only for current request, so you can use it as a storage for any request related information.
When the request is responded, it's garbage.
So I have a little helper method that will return the login URL for the DotNetNuke site but it only works if you have the (PortalSettings and HttpRequest objects).
Unfortunately, calling on the DNN static method:
PortalController.GetCurrentPortalSettings
Doesn't return the PortalSettings object if my session hasn't registered with DNN. My situation is that I have a ajax calls to a web method that I would like to retrieve the login url and return the string to the page in order to redirect a user to the login page who's session timed out.
Unfortunately, it return's null.
Message":"Value cannot be null.\r\nParameter name: portalSettings","StackTrace":"
The PortalController method is returning null.
Any thoughts?
Try adding portalId as a querystring parameter in your AJAX request (i.e instead of /DesktopModules/MyModule/Service.asmx use /DesktopModules/MyModules/Service.asmx?portalId=1). This should let DNN process the request enough to create a PortalSettings object.
I'm trying to get a user ID stored in cookies via a common Controller file, which I can access throughout the site.
I have created FunctionsController as a controller, with content as follows:
public static int loggedinUser()
{
return Convert.ToInt32( request.Cookies["userid"].Value);
}
I am unable to request any cookie items even if I tried with:
HttpRequestBase request = controllerContext.HttpContext.Request;
I don't have a problem accessing cookies in ASP.NET MVC using a standard access statement such as:
Request.Cookies["someCookie"]
Your sample had a lower-cased "r" in "request.Cookies". Could that be your problem?
Remove the static part of your method declaration and then use Request.Cookies["userId"]