This is my first question here so I am very excited. :)
I am developing a car rental project with C# for backend and Angular for front end. When I try to register a new user with data of an existing user, I get attached response in Postman. The controller in backend sends a Badrequest with a message "User already exists!". I tried to control this at Front End side in Angular. What I would like to do is, just to recognize this error with an IF statement and show this message "User already exists!" on the web page with a toastr service. However, I can not detect it in Angular at all. Can you please help me? How can I take this backend response into control in Angular? Thanks in advance for your help!
Code in Controller:
[HttpPost("register")]
public ActionResult Register(UserForRegisterDto userForRegisterDto)
{
var userExists = _authService.CheckIfUserExists(userForRegisterDto.Email);
if (!userExists.Success)
{
return BadRequest(userExists.Message);
}
var registerResult = _authService.Register(userForRegisterDto, userForRegisterDto.Password);
var result = _authService.CreateAccessToken(registerResult.Data);
if (result.Success)
{
return Ok(result.Data);
}
return BadRequest(result.Message);
}
To return a specific response code with a message from backend:
return new HttpStatusCodeResult(errorCode, "Message");
Make sure the method in the controller is type ActionResult, not ViewResult.
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 have built a Web API that is connected to a database for persons. I am now trying to call this Web API from a separate MVC-application which is supposed to have full CRUD. So far i have managed to do so with the Get and Post-methods to create a new person and see a list of the persons currently in the database.
When trying to do a similar call for the Put-method, i get the following error:
This is how my method UpdatePerson is written in my API-application:
[HttpPut]
[Route("{id:guid}")]
public async Task<IActionResult> UpdatePerson([FromRoute] Guid id, UpdatePersonRequest updatePersonRequest)
{
var person = await dbContext.Persons.FindAsync(id);
if (person != null)
{
person.Name = updatePersonRequest.Name;
person.Email = updatePersonRequest.Email;
person.Phone = updatePersonRequest.Phone;
person.Address = updatePersonRequest.Address;
await dbContext.SaveChangesAsync();
return Ok(person);
}
And this is how i am trying to consume the API in my separate MVC-project:
[HttpGet]
public IActionResult Edit()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Edit(PersonViewModel pvm)
{
HttpClient client = new();
StringContent sContent = new StringContent(JsonConvert.SerializeObject(pvm), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PutAsync("https://localhost:7281/api/Persons/", sContent);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Get");
}
else
{
return NotFound();
}
}
Everything is working fine when i try to update the database through the API-app so i am not really sure what is wrong with my request. I hope that someone here can spot the issue right away or at least help me out as i am quite a beginner with WEB APIs.
I have mostly tried changing the URL in my MVC-project but the issue remains.
Are you sure you are receiving the request? It seems that your URI is
"https://localhost:7281/api/Persons/"
and your API is expecting
"https://localhost:7281/api/Persons/{id}" -> where {id} should be the guid
you need to append the guid in the URI
Looks like the request doesn't receive the correct the correct parameters, because the URI that appears in your picture seems a generic method.
I have a method in Api as follows
[HttpPut]
[Route("UpdateTeacher")]
public IHttpActionResult UpdateTeacher(BusinessLayerTeacher Obj)
{
try
{
BusinessLayerTeacher obj = new BusinessLayerTeacher ();
string status = BusinessLayerObject.UpdateTeacher(TeacherObj);
return Ok(status);
}
catch
{
return NotFound();
}
}
Now in post man i am sending the put request to update the teacher object.
It is not triggering this updateTeacher() method.
You are instantiating a new BusinessLayerTeacher object inside the method, which looks suspect when you are already passing in BusinessLayerTeacher as a parameter.
Maybe the route mapping isn't working because you're not passing in the right data in the request body.
Maybe you should be using TeacherObj as the parameter type?
Have a review and give that a try, good luck :-)
I am developing web site in angular js, .net web api 2, visual studio 2013, and c#.
My url navigation is purely driven by angularjs.
Upon password reset, I email a link to the user that looks like this:
http://localhost:3458/api/Account/ResetPasswordEmail?userId=xxxxxxxxxxxxxxxx9049a8e3-fb90-400a-b73e-78cadc16ae40&code=BVEssssssssssssssssssswT9FsJ3QncMLaPclhLZVUHpHifX8wmG7f3ZrlxDlwkkmcMNccdXz8jdEuGdHM1FJ4WdBu9Yxu9VG43DxamBrasdfasdfasdfbdasdfvgGrqwJxRoJ%2FSCDkOrbV3RupmUaoTgRmebwb1ymBZwkd891G3q6SW%2F%2FTDwOQ7qrkzkAUYtjcwd%2FTH4jNNCzIYmMXF%2BkMF26mBM4Osgc%2Bi%2BO0So41%2Fpp3yK%2BDvEtNCPA%3D%3D&newPassword=xxxxxxxxxx
User receives the email and clicks on the link..
On the server side, following code is executed:
//
// GET: /Account/ResetPasswordEmail
// GET api/Account/ResetPasswordEmail
[Route("ResetPasswordEmail", Name = "ResetPasswordEmail")]
[AllowAnonymous]
public HttpResponseMessage GetResetPasswordEmail(string userId, string code, string newPassword)
{
string errmsg = string.Empty;
try
{
if (userId == null || code == null)
{
errmsg = "Either email address or other necessary parameter is null.";
throw new Exception(errmsg);
}
var result = UserManager.ResetPasswordAsync(userId, code, newPassword);
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
return response;
}
catch(Exception ex)
{
return null;
}
}
The password is reset successfully...
However ...
I want to give visual feedback on the web page that password was or was not reset successfully. In other words, in this situation how would my web api talk back to the angular js code to render a UI. Would I resort to some sort of asp.net mvc type of code?
In your website project's controller folder need to add action which where user will land from email
Then call api from that action if success then return success view in that action
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