WEB API - 如何使用身份向用户中的自定义 属性 添加值

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

在 WEB 中使用身份 API 我创建了一些保存在 SQL 数据库。我已将自定义 属性 (ShippingAddress) 添加到使用 Identity 创建的用户 table 附带的默认属性中。

创建用户时,我输入:用户名、电子邮件和密码来创建用户。我希望稍后添加送货地址。

我需要将送货地址添加到当前登录的用户。(我登录或注销都没有问题)。

这是我尝试过的:

当我点击这个按钮时,我在警告框中得到了当前登录的用户名。 这行得通。

 <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) {
                }
            });
        });

这不起作用。 添加送货地址的按钮是:

 <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) {
                }
            });
        });

这给了我这个错误:

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

这些是控制器:

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();
        }
    }
}

我不知道我的问题是在 ajax 请求、控制器还是两者。有人可以帮忙吗?

这里的问题出在 addAddress() 控制器中;

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

.Find() 方法仅适用于主键。在我的情况下,我没有使用主键。我不知道为什么它在 visual studio 中没有给我任何错误,但错误发生在浏览器控制台中。无论如何......如果我这样改变它一切正常。

using Microsoft.AspNet.Identity;
...

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

我们需要添加 "using Microsoft.AspNet.Identity;" 方法 .GetUserId() 才能工作。