簡體   English   中英

WEB API - 如何使用身份為用戶中的自定義屬性添加值

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

將身份與 WEB API 結合使用,我創建了一些保存在 SQL 數據庫中的用戶。 我已將自定義屬性 (ShippingAddress) 添加到使用 Identity 創建的用戶表附帶的默認屬性中。

當我創建用戶時,我輸入:用戶名、電子郵件和密碼來創建用戶。 我希望稍后添加送貨地址。

我需要向當前登錄的用戶添加送貨地址。(我登錄或退出都沒有問題)。

這是我嘗試過的:

當我單擊此按鈕時,我會在當前登錄的警報框中獲取用戶名。這是有效的。

 <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(內部服務器錯誤)

這些是控制器:

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

我們需要添加“使用 Microsoft.AspNet.Identity;” 方法 .GetUserId() 工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM