Search code examples
javascriptjqueryasp.net-web-api2asp.net-identity

WEB API - how to add value to custom property in User using identity


Using Identity with WEB API i have created some users that are saved in SQL database. I have added custom property (ShippingAddress) to the already default properties that come with the User table created with Identity.

When i create the user i put : username, email and password to create the user. I want the shipping address to be added later on.

I need to add the shipping address to the user that is currently logged in. (I have no problems logging in or out).

Here is what i have tried:

When I click this Button i get the username in alert box that is currently logged in. This works.

 <button id="GetUserName">GetUserName</button>

 $('#GetUserName').click(function () {
        $.ajax({
                url: 'GetUserName',
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer '
                        + sessionStorage.getItem("accessToken")
                },
                success: function (data) {
                    alert(data);
                },
                error: function (jQXHR) {
                }
            });
        });

This Does not work. The Button for Adding the Shipping Address is:

 <button id="addAddress">addAddress</button>

   $('#addAddress').click(function () {
            $.ajax({
                url: 'addAddress',
                method: 'PUT',
                headers: {
                    'Authorization': 'Bearer '
                        + sessionStorage.getItem("accessToken")
                },
                //success: function (data) {
                //    alert(data);
                //},
                error: function (jQXHR) {
                }
            });
        });

This gives me this error:

jquery-3.3.1.min.js:2 PUT http://localhost:64687/addAddress 500 (Internal Server Error)

These are the controllers:

using EmployeeService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace EmployeeService.Controllers
{
    public class EmployeesController : ApiController
    {
        ApplicationDbContext db = new ApplicationDbContext();


        [Route("GetUserName")]
        public string GetName()
        {
            string x = User.Identity.Name;
            return x;
        }

        [Route("addAddress")]
       [HttpPut]
        public void addAddress()
        {
            string x = User.Identity.Name;
            var myUser =  db.Users.Find(x);
            myUser.ShippingAdress = "asdasd";
            db.SaveChanges();
        }
    }
}

I dont know if my problem is in the ajax request, the controller or both. Can someone please help.


Solution

  • The problem here was in the addAddress() controller;

    string x = User.Identity.Name;   // here is the problem
    var myUser =  db.Users.Find(x); // here is the problem
    myUser.ShippingAdress = "asdasd";
    

    The method .Find() works only with primary keys. In my situation i didn't use the primary key. I don't know why it didn't give me any errors in the visual studio but the error occurred in the browser console. Anyway... if i change it like this everything works fine.

    using Microsoft.AspNet.Identity;
    ...
    
    string x = User.Identity.GetUserId(); // we changed this
    var myUser =  db.Users.Find(x); 
    myUser.ShippingAdress = "asdasd";
    

    We need to add "using Microsoft.AspNet.Identity;" for the method .GetUserId() to work.