I'm using asp.net mvc,
I have a POST Method that called from an outside service(differnet domain) and i want when it called to get data from my site.
Before the method was called I tried to save that data in Session object and in a Cookie,
But the data is not there.
Maybe it could be because the post request sent from a different domain?
What am I doing wrong?
[HttpPost]
public ActionResult Callback(Callback callback)
{
Not Working ->
var userMail = HttpContext.Request.Cookies.Get("Current")["UserMail"];
}
public ActionResult SomeSitePage()
{
var cookie = new HttpCookie("Current");
var userMail = (Session["user"] as ApplicationUser).Email;
cookie["UserMail"] = userMail;
HttpContext.Response.Cookies.Add(cookie);
}
Thanks.
Apparently If a post method is called from another domain,
saving data in session or cookies does not count,
I needed to save it in the database first and then pull it out in the post method.
Related
I have a web application I am developing that depends on back end processing. I am sending a post request from my Angular(v14)/Typescript front end to an ASP.NET back end.
Back end code
[HttpPost]
public async Task<string> ProcessExcelFile(IFormFile fileData, IFormCollection data)
{
string guid = await processor.ProcessFile(fileData, data) //Imp not important for question.
return guid;
}
Front end code
var guid: string = "";
this.http.post<string>('/api', formData).subscribe(result => {guid = result;});
I have confirmed the backend is being hit correctly through debugging and returns the correct data.
But the front end "guid" is empty after I call the post request. What I am doing wrong here?
The back end processing could take a few seconds, is that the problem? What can I do about this?
In case it's a JSON response you should be able to do it like this:
// Backend response
{
"guid": "randomId123",
}
let guid: string;
this.http.post<any>('/api', formData).subscribe(result => {
guid = result.guid;
});
If it's not JSON Response, could please share how the response look alike?
Update in case the response is just text:
let guid: string;
this.http.post<string>('/api', formData,{ responseType:'text'}).subscribe(result => {
guid = result;
});
Just by going through the code snippets, not returning an IActionResult stands out to me so you could give this is a shot and check if it solves the issue
[HttpPost]
public async Task<IActionResult> ProcessExcelFile(IFormFile fileData, IFormCollection data)
{
string guid = await
processor.ProcessFile(fileData, data) //Imp not important for question.
return ok(guid);
}
This basically sends an OK API response with the guid as the content
It looks like the post request would not finalize until the function it lived in that started from a button click on the web page finished.
Instead of creating the guid variable in the same function as the post request, I changed it to a global variable. I am now getting the correct data in the guid variable but only after the button press function finishes.
this.http.post<string>('/api', formData).subscribe(result => {this.guid = result;});
I got a url where it's method is post but I want to pass some paramets by get method, I am using c# MVC asp.net
as the follow link
http://site/api/user/seach/?value=here&value2=here2
I am trying to get this using
public IHttpActionResult Get()
{
var queryString = this.Request.GetQueryNameValuePairs();
}
And I already tried to use
string p = Request.QueryString["value"];
But it seems to work only in controller base exteds
Is there some way to get this value get in a post method ?
Sounds like you'd like to use the POST verb but send data through querystring, in that case you can:
public IHttpActionResult Post([FromUri]string value)
{
// do whatever you need to do here
}
Implementing a MVC application in C# with Evernote API. I am using the AsyncOAuth.Evernote.Simple nuget package. Receiving and error of Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN', when trying to navigate to URL that fires off the OAuth process.
There is an iframe that is surrounding my code (which can not be altered). After implementing the code an error is generated: "An item with the same key has already been added". This error occurs when requestToken is hit for the first time.
Below is my EvernoteProviderController.cs
public class EvernoteProviderController : Controller
{
// Initialize Oauth call, pulling values from web.config
EvernoteAuthorizer EvernoteAuthorizer = new EvernoteAuthorizer(ConfigurationManager.AppSettings["Evernote.Url"] + "&output=embed", ConfigurationManager.AppSettings["Evernote.Key"], ConfigurationManager.AppSettings["Evernote.Secret"]);
// This method makes the original call to Evernote to get a token so that the user can validate that they want to access this site.
public ActionResult Authorize(bool reauth = false)
{
// Allow for reauth
if (reauth)
SessionHelper.Clear();
// First of all, check to see if the user is already registered, in which case tell them that
if (SessionHelper.EvernoteCredentials != null)
return Redirect(Url.Action("AlreadyAuthorized"));
// Evernote will redirect the user to this URL once they have authorized your application
var callBackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action("ObtainTokenCredentials");
// Generate a request token - this needs to be persisted till the callback
var requestToken = EvernoteAuthorizer.GetRequestToken(callBackUrl);
// Persist the token
SessionHelper.RequestToken = requestToken;
// Redirect the user to Evernote so they can authorize the app
var callForwardUrl = EvernoteAuthorizer.BuildAuthorizeUrl(requestToken);
return Redirect(callForwardUrl);
}
// This action is the callback that Evernote will redirect to after the call to Authorize above
public ActionResult ObtainTokenCredentials(string oauth_verifier)
{
// Use the verifier to get all the user details we need and store them in EvernoteCredentials
var credentials = EvernoteAuthorizer.ParseAccessToken(oauth_verifier, SessionHelper.RequestToken);
if (credentials != null)
{
SessionHelper.EvernoteCredentials = credentials;
return Redirect(Url.Action("Authorized"));
}
else
{
return Redirect(Url.Action("Unauthorized"));
}
}
// Show the user if they are authorized
public ActionResult Authorized()
{
return View(SessionHelper.EvernoteCredentials);
}
public ActionResult Unauthorized()
{
return View();
}
//Redirects user if already authorized, then dump out the EvernoteCredentials object
public ActionResult AlreadyAuthorized()
{
return View(SessionHelper.EvernoteCredentials);
}
public ActionResult Settings()
{
return View();
}
}
Has anyone had this issue with iframes before or knows in what direction I should go? I am trying to embed my URL endpoint so I can get around the iframe error.
Solved the error.
A bit of back story:
The purpose of this application was to provide the OAuth page where a user can sign up which will generate a AuthToken and NotebookURL, (both are needed with Evernote API to pull read/write Notes - which is Evernote's object).
The previous behavior (before I changed it), was when a user clicked on the link - they will be redirected (in the same window) to the Evernote OAuth page.
This caused issues for me, because I had another wrapper around my code (iframe). So in non-technical terms, I had a iframe within an iframe within an iframe.
Workaround
Created a JavaScript code which would add an click event listener, which would then create a popup using window.open.
$("#btnStart").click(function () {
myWindow = window.open(baseUrl + "/EvernoteProvider/Authorize", '_blank', 'width=500,height=500, scrollbars=no,resizable=no');
myWindow.focus();
});
Today I've been trying to program a little bit in the MVC 4 Facebook API developed by Microsoft (based on the example of: http://www.asp.net/mvc/tutorials/mvc-4/aspnet-mvc-facebook-birthday-app)
So far I managed to manipulate the MyAppUser model, etc. Everything working fine and as intended. I only have a slight problem when I'm switching through controllers.
Is there any way to retain the FacebookContext object through controllers?
Unfortunately the above example (from Microsoft) only loads MyAppUser in the Home controller as follows:
[FacebookAuthorize("email", "user_photos")]
public async Task<ActionResult> Index(FacebookContext context) {
if (ModelState.IsValid) {
var user = await context.Client.GetCurrentUserAsync<MyAppUser>();
return View(user);
}
return View("Error");
}
What should I do if I use another controller in the application? How can I obtain a FacebookContext reference to get the user?
Things I tried:
Putting FacebookContext context into the other Controller (is always null)
Putting the FacebookContext object into Session or ViewBag - no avail, and sounds way too dirty anyway.
Am I missing something crucial here?
I just wanted to have a different Controller with a couple of actions to manage a User's profile, which would be done completely separately from Facebook's data (via a database hosted locally.) The only reason I need to load the Context is to get the current user's e-mail address to create their account on that basis.
Any help would be greatly appreciated as I've spent quite a considerable amount of time trying to fix it.
My example controller could be:
public ActionResult Manage()
{
var user = await context.Client.GetCurrentUserAsync<Models.MyAppUser>();
if (MyDALFunction.GetUserByMail(user.Email) == null) {
// Create user functions, create a ViewModel, pass it on and do some editing.
}
return View(user);
}
This is how I solved this:
First, in Home Controller I save access token to TempData
public async Task<ActionResult> Index(FacebookContext context)
{
if (ModelState.IsValid)
{
this.TempData["accessToken"] = context.AccessToken;
Then I read it in another action in different controller. If access token is empty, it means that user is not logged in, so I redirect him to Home controller.
var accessToken = TempData["accessToken"] as string;
if (string.IsNullOrEmpty(accessToken))
{
//if access token is null or user is not logged in, redirect to home controller
return RedirectToAction("Index", "Home");
}
else
{
var fb = new Facebook.FacebookClient(accessToken);
var me = fb.Get("me") as Facebook.JsonObject; //current logged user
var userFacebookId = me["id"].ToString();
Instead of "id", you can read email.
EDIT:
Retrieving accessToken from TempData returned null, when i tried to do that in another controller. It would be better to store it in Session instead.
Where to store Facebook access token in ASP.NET MVC?
Sorry, for answering too late.. but if i understood your question correctly then i think you are trying to get the FacebookContext object in you Action Method when post-back occurs. If so, then.. In your .cshtml try to put
<a target="_top" href="#GlobalFacebookConfiguration.Configuration.AppUrl#Url.Action("Manage", new { friendId = friend.Id })" role="button" class="btn btn-success">
and then make you action method like...
public ActionResult Manage(string friendId, FacebookContext context)
{
var friend = await context.Client.GetFacebookObjectAsync<MyAppUserFriend>(friendId);
// var user = await context.Client.GetCurrentUserAsync<Models.MyAppUser>();
if (MyDALFunction.GetUserByMail(friend.Email) == null) {
// Create user functions, create a ViewModel, pass it on and do some editing.
}
return View(user);
}
But Make sure that your MyAppUserFriend model have the Email attribute..
If you wanted any thing else then please provide some detail of you Model and your View
I am playing around again with ASP.NET, and tried to set a cookie in one action which will be read in another action.
The strange thing is: the cookie gets set, but looses its value when accessing another page. Here is my simple controller code:
public class HomeController : Controller
{
public ActionResult About()
{
var cookie = Response.Cookies.Get("sid");
ViewData["debug"] = "Id: " + cookie.Value;
return View();
}
public ActionResult DoLogin()
{
var cookie = new HttpCookie("sid", Guid.NewGuid().ToString());
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
return RedirectToAction("About");
}
}
The flow is like this: first I access /Home/DoLogin, then I get redirected to /Home/About which should actually output the value of the sid cookie. But the cookie does not have any value.
Cookies are not disabled in my browser
I know that ASP.NET has its own session handling mechanism, just playing around and stumbled upon this cookie problem
Thanks for any hints!
In your About action, use Request.Cookies instead.
As a short explanation: When you set something in Response.Cookies, that cookie is sent to the client which stores it. On each subsequent Request to the same namespace, until the expiry date is reached, the client sends that cookie to the server, which stores it in Request.Cookies.