gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:14:06 27 4
gpt4 key购买 nike

通过 WEB API 使用 Identity 我已经创建了一些保存在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 (Internal Server Error)

这些是 Controller :

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 请求、 Controller 还是两者。有人可以帮忙吗?

最佳答案

这里的问题出在 addAddress() Controller 中;

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() 起作用。

关于javascript - WEB API - 如何使用身份向用户中的自定义属性添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52084860/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com