How do I access Request.cookies in an ASP.NET MVC controller? - c#

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"]

Related

Failed to load resource: the server responded with a status of 404 ()

I am writing a REST API in .net core. I am trying to test the API using Postman and I am getting an error saying
Failed to load resource: the server responded with a status of 404 ()
I know this error occurs when the route does not match. Not sure, what am I doing wrong with the route. Below is my code with the Route at the top:
namespace RecLoad.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RecLoadPrimeController : ControllerBase
{
[Route("RecLoadPrime/insertRecLoadData/{RecStartDate}/{RecEndDate}")]
[HttpPost]
public void insertRecLoadData(string RecStartDate, string RecEndDate)
{
RecLoadDataProvider dataProvider = new RecLoadDataProvider();
dataProvider.InsertCardsData(RecStartDate, RecEndDate);
}
}
}
The URL that I am trying to test in Postman is below:
https://localhost:44360/api/RecLoadPrime/insertRecLoadData/?RecStartDate=01/01/2020&RecEndDate=01/02/2020
I am very new to API, this is the first API that I am writing. Below is the image for application structure. Its extremely simple:
Any help will be greatly appreciated.
A 404 error means not found. This means Postman cant find the end point you are trying to hit.
Your [Route] attribute needs to be updated. The root of this endpoint (controller) it's RecLoadPrime. So get rid of that part. If you are just trying to test, update it to [Route("insert")].
Using ? in your URL means you are passing query parameters. Which are usually used on GET requests not on POST requests.
Web API expects you to use Model Binding for passing in parameters. Meaning map the post parameters to a strongly typed .NET object, not to single parameters. Alternatively, you can also accept a FormDataCollection parameter on your API method to get a name value collection of all POSTed values.
For example: Create a small class called Card, with the properties startDate, and endDate. Make them DateTime. Now use that in the method signature public void insertRecLoadData([FromBody]Card card)
In Postman, you are now going to use the Body option and create a JSON representation of this new class we created.
For example: { "startDate": "2020-03-23", "endDate": "2020-03-27" }
In the route, you are going to use: POST | https://localhost:44360/api/insertRecLoadData/insert
Make sure you set breakpoints in your controller. Not sure how you have setup your project but I'd suggest reading up more on how to setup a Web API using ASP.NET Core. Look into RESTful design to also get an idea on how to best setup these end points.
Good luck!
The current route configuration on your controller and on your action will result in duplicated section in your route. Specifically, the route the action will be associated with will be "api/RecLoadPrime/RecLoadPrime/insertRecLoadData/{RecStartDate}/{RecEndDate}".
Consider removing the RecLoadPrim/ prefix from your action route attribute as follows:
[Route("insertRecLoadData/{RecStartDate}/{RecEndDate}")]

web api get user info inside controller

I'm using the standard owin asp.net.identity mechanism to authorize users using their access token. Inside my controller I would like to find out who has sent the request. How could I do it? Could I somehow retrieve the access token from the request inside my controller?
I have tried:
public HttpResponseMessage Get([FromUri] GetParameters parameters)
{
Var identity = RequestContext.Principal.Identity;
}
It does not give me a lot as majority of properties are always null.
try
string token = HttpContext.Current.Request.LogonUserIdentity.Token.ToString();

Get access to HttpActionContext outside of my Web API 2 Controller

Inside my Controller class I can do this:
var userId = this.ActionContext.RequestContext.Principal.Identity.Name;
But I have a soap header that I want to pass this value into. The behavior that uses the soap header is setup using my dependency injection. So while it is created for each call, it is not created in the Controller.
So I am wondering, is there a way to get access to Web API 2's HttpActionContext outside the controller. Ideally I would want something like this:\
HttpActionContext.CurrentInstance.RequestContext.Principal.Identity.Name;
But of course CurrentInstance does not exist as a static member of HttpActionContext.
But is there some other way to get this without the Controller?
You can access identity name using following
System.Web.HttpContext.Current.User.Identity.Name

create cookie in web method

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.

MVC - Passing Data with RedirectToAction()

I'd like to take data entered in an MVC user form and display it in a different view.
The class has the following private variable:
IList<string> _pagecontent = new List<string>();
The following action accepts a FormCollection object, validates it, and passes it on to the "Preview" view as a List:
[Authorize(Roles = "Admins")]
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateContent(FormCollection collection)
{
if (ModelState.IsValid)
{
string PageToInsert = collection["PageToInsert"];
string PageHeader = collection["PageHeader"];
string PageBody = collection["PageBody"];
//validate, excluded...
_pagecontent.Add(PageToInsert);
_pagecontent.Add(PageHeader);
_pagecontent.Add(PageBody);
}
return RedirectToAction("Preview", _pagecontent);
}
The Preview view has the following Page Directive for passing a strongly typed object List:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Template.Master" Inherits="System.Web.Mvc.ViewPage<List<string>>" %>
I would expect to be able to use the Model object to get my data, but alas I cannot. At the following line, I get an error index out of bounds exception, stating the index must be non-negative and less than the size of the collection:
<% if (Model[0].ToString() == "0") { %>
And some strange parameters have been added to the URL, as it resolves to
http://localhost:1894/Admin/Preview?Capacity=4&Count=3
So I have two questions:
When I call RedirectToAction and pass it my List, why is it inaccessible in the view's Model object?
What is the proper way to go about doing what I'm trying to do, namely pass a collection of strings to a view for display there?
Try using TempData. It is like a single-shot session object. You put values you want into TempData, immediately redirect and get them out. There is a good writeup here: http://blogs.teamb.com/craigstuntz/2009/01/23/37947/
Be careful when using TempData. It works great in a single server environment but in a cloud environment it may not work as expected since you cannot guarantee that the request will hit the same machine. This happens because TempData rely on the asp.net session. But if you are using other session manager like SQL or AppFabric Cache it will work fine.
The second parameter to RedirectAction is routeValues, not model.
protected internal RedirectToRouteResult RedirectToAction(string actionName, object routeValues);
Try using TempData for the model. Its for persisting data between redirects.
The problem with RedirectToAction is it's returning a HTTP 302 and the browser is then on it's own going and doing a brand new HTTP request. You may want to consider using a cookie and/or session object to persist the data between requests.
This is not working because RedirectToAction is actually sending back a Http 302 to the browser. When the browser receives this 302, it does a new request to the server asking for the new page. New request, new temp variables.
You will also face this problem when you try to save/edit/delete something and for some reason you deny it and you have to return the old form again.
So, instead of:
return RedirectToAction("Preview", _pagecontent);
Put the Preview logic in a separate method and just call it:
return PreviewLogic(_pagecontent);
You can also use the TempData[] dic to persist data for the next request like others have said, but then you will not avoid the 302 additional round trip to the server.
It sounds like you're trying to do:
public ActionResult UpdateContent(FormCollection form) {
...
return View("Preview", _pagecontent);
}
Note that a redirection is supposed to be a "clean slate" for the browser (except for things like the auth cookie). You don't get to tell the browser to pass information along to the next request, since the next request should be able to stand on its own. All you get to do is tell the browser what URL to request next. In ASP.NET MVC, when you pass an arguments-object to RedirectToAction, the public properties of that object are appended as query-string parameters to the generated URL.
Can't you just make 2 action results with the same name and mark 1 of them with HttpPost?
public ActionResult UpdateContent(FormCollection preview = null)
{
return View(preview);
}
[HttpPost]
public ActionResult UpdateContent(FormCollection collection = null, bool preview = false)
{
if (preview)
return UpdateContent(collection);
else
return UpdateContent(null);
}
It looks like you are looking for the UpdateModel command:
Check out ScottGu's blog post on the topic:
Improved UpdateModel and TryUpdateModel methods

Categories

Resources