当前位置: 首页 > 知识库问答 >
问题:

.Netcore Api Postman 500内部服务器错误

苗承
2023-03-14

通过postman从API到数据库的post请求给了我以下响应:{“message”:“无效的对象名‘Accounts’。”}

这些是我的C#代码,我不知道我做错了什么或我错过了什么。请帮助。

>

  • 帐户控制器。

    使用AutoMapper;使用Microsoft。AspNetCore。Http;使用Microsoft。AspNetCore。Mvc;使用系统;使用系统。集合。通用;使用非洲生物医学测试。实体;使用非洲生物医学测试。模型。帐户;使用非洲生物医学测试。服务;

     namespace Africanbiomedtests.Controllers
     {
         [ApiController]
         [Route("[controller]")]
         public class AccountsController : BaseController
         {
              private readonly IAccountService _accountService;
              private readonly IMapper _mapper;
    
              public AccountsController(
                  IAccountService accountService,
                  IMapper mapper)
              {
                  _accountService = accountService;
                  _mapper = mapper;
             }
    
             [HttpPost("authenticate")]
             public ActionResult<AuthenticateResponse> Authenticate(AuthenticateRequest model)
             {
                 var response = _accountService.Authenticate(model, ipAddress());
                 setTokenCookie(response.RefreshToken);
                 return Ok(response);
             }
    
             [HttpPost("refresh-token")]
             public ActionResult<AuthenticateResponse> RefreshToken()
             {
                 var refreshToken = Request.Cookies["refreshToken"];
                 var response = _accountService.RefreshToken(refreshToken, ipAddress());
                 setTokenCookie(response.RefreshToken);
                 return Ok(response);
             }
    
             [Authorize]
             [HttpPost("revoke-token")]
             public IActionResult RevokeToken(RevokeTokenRequest model)
             {
                 // accept token from request body or cookie
                 var token = model.Token ?? Request.Cookies["refreshToken"];
    
                 if (string.IsNullOrEmpty(token))
                     return BadRequest(new { message = "Token is required" });
    
                 // users can revoke their own tokens and admins can revoke any tokens
                 if (!Account.OwnsToken(token) && Account.Role != Role.Admin)
                     return Unauthorized(new { message = "Unauthorized" });
    
                 _accountService.RevokeToken(token, ipAddress());
                 return Ok(new { message = "Token revoked" });
             }
    
             [HttpPost("register")]
             public IActionResult Register(RegisterRequest model)
             {
                 _accountService.Register(model, Request.Headers["origin"]);
                 return Ok(new { message = "Registration successful, please check your email for verification instructions" });
             }
    
             [HttpPost("verify-email")]
             public IActionResult VerifyEmail(VerifyEmailRequest model)
             {
                 _accountService.VerifyEmail(model.Token);
                 return Ok(new { message = "Verification successful, you can now login" });
             }
    
             [HttpPost("forgot-password")]
             public IActionResult ForgotPassword(ForgotPasswordRequest model)
             {
                 _accountService.ForgotPassword(model, Request.Headers["origin"]);
                 return Ok(new { message = "Please check your email for password reset instructions" });
             }
    
             [HttpPost("validate-reset-token")]
             public IActionResult ValidateResetToken(ValidateResetTokenRequest model)
             {
                 _accountService.ValidateResetToken(model);
                 return Ok(new { message = "Token is valid" });
             }
    
             [HttpPost("reset-password")]
             public IActionResult ResetPassword(ResetPasswordRequest model)
             {
                 _accountService.ResetPassword(model);
                 return Ok(new { message = "Password reset successful, you can now login" });
             }
    
             [Authorize(Role.Admin)]
             [HttpGet]
             public ActionResult<IEnumerable<AccountResponse>> GetAll()
             {
                 var accounts = _accountService.GetAll();
                 return Ok(accounts);
             }
    
             [Authorize]
             [HttpGet("{id:int}")]
             public ActionResult<AccountResponse> GetById(int id)
             {
                 // users can get their own account and admins can get any account
                 if (id != Account.Id && Account.Role != Role.Admin)
                     return Unauthorized(new { message = "Unauthorized" });
    
                 var account = _accountService.GetById(id);
                 return Ok(account);
             }
    
             [Authorize(Role.Admin)]
             [HttpPost]
             public ActionResult<AccountResponse> Create(CreateRequest model)
             {
                 var account = _accountService.Create(model);
                 return Ok(account);
             }
    
             [Authorize]
             [HttpPut("{id:int}")]
             public ActionResult<AccountResponse> Update(int id, UpdateRequest model)
             {
                 // users can update their own account and admins can update any account
                 if (id != Account.Id && Account.Role != Role.Admin)
                     return Unauthorized(new { message = "Unauthorized" });
    
                 // only admins can update role
                 if (Account.Role != Role.Admin)
                     model.Role = null;
    
                 var account = _accountService.Update(id, model);
                 return Ok(account);
             }
    
             [Authorize]
             [HttpDelete("{id:int}")]
             public IActionResult Delete(int id)
             {
                 // users can delete their own account and admins can delete any account
                 if (id != Account.Id && Account.Role != Role.Admin)
                     return Unauthorized(new { message = "Unauthorized" });
    
                 _accountService.Delete(id);
                 return Ok(new { message = "Account deleted successfully" });
             }
    
             // helper methods
    
             private void setTokenCookie(string token)
             {
                 var cookieOptions = new CookieOptions
                 {
                     HttpOnly = true,
                     Expires = DateTime.UtcNow.AddDays(7)
                 };
                 Response.Cookies.Append("refreshToken", token, cookieOptions);
             }
    
             private string ipAddress()
             {
                 if (Request.Headers.ContainsKey("X-Forwarded-For"))
                     return Request.Headers["X-Forwarded-For"];
                 else
                     return HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             }
         }
     }
    

    2).账户实体

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Africanbiomedtests.Entities
    {
        public class Account
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Email { get; set; }
            public string PasswordHash { get; set; }
            public bool AcceptTerms { get; set; }
            public Role Role { get; set; }
            public HealthcareProvider HealthcareProvider { get; set; }
            public string VerificationToken { get; set; }
            public DateTime? Verified { get; set; }
            public bool IsVerified => Verified.HasValue || PasswordReset.HasValue;
            public string ResetToken { get; set; }
            public DateTime? ResetTokenExpires { get; set; }
            public DateTime? PasswordReset { get; set; }
            public DateTime Created { get; set; }
            public DateTime? Updated { get; set; }
            public List<RefreshToken> RefreshTokens { get; set; }
    
            public bool OwnsToken(string token) 
            {
                return this.RefreshTokens?.Find(x => x.Token == token) != null;
            }
        }
    }
    

    3) 。RegisterRequest模型

    using System.ComponentModel.DataAnnotations;
    
    namespace Africanbiomedtests.Models.Accounts
    {
        public class RegisterRequest
        {
            [Required]
            public string Title { get; set; }
    
            [Required]
            [StringLength(30)]
            [RegularExpression(@"^[A-Z]+[a-zA-Z]*$")]
            public string FirstName { get; set; }
    
            [Required]
            [StringLength(30)]
            [RegularExpression(@"^[A-Z]+[a-zA-Z]*$")]
            public string LastName { get; set; }
    
            [Required]
            [EmailAddress]
            public string Email { get; set; }
    
            [Required]
            [MinLength(6)]
            public string Password { get; set; }
    
            [Required]
            [Compare("Password")]
            public string ConfirmPassword { get; set; }
    
            [Range(typeof(bool), "true", "true")]
            public bool AcceptTerms { get; set; }
        }
    }
    
  • 共有1个答案

    张森
    2023-03-14

    感谢John的帮助,我意识到我没有完成EF数据库迁移,所以故障是我造成的。迁移了吗,现在正在工作。

     类似资料:
    • 我是新的角度6。我用spring boot开发了一个post服务,当我通过postman测试它时,它工作得很好,但当我用web浏览器测试它时,它给了我这个错误: HttpErrorResponse ;{headers:HttpHeaders,status:500,statusText:“ok”,URL:“http://localhost:8080/api/test/ordermiss”,ok:fa

    • 我用wordpress和woocommerce(www.jescesole.eu)建立了一个网站。由于该网站在德国销售,我不得不在最近几天安装一个附加插件,woocommerce germanized(与polylang一起,以德语和意大利语查看内容),我升级了wp和所有插件,但当客户提交订单时,会出现一条内部服务器错误消息。我阅读了服务器错误日志,并报告了一条很长的错误消息: 周四,13四月20

    • 问题内容: 我正在尝试为这个工作中的项目学习AJAX。我有一个网站加载病人正在服用的药物。 我递归调用此AJAX函数,以便它将附加一个包含单种药物和7天历史记录的新表。我在使代码在FF和IE中执行时遇到问题。在chrome中效果很好。我有显示xmlhttp.status的警报,这是我得到的: xmlhttp.status == 500(内部服务器错误)。 我注释掉了所有递归,因此将其范围缩小到了这

    • 我收到以下错误 内部服务器错误 服务器遇到内部错误或配置错误,无法完成您的请求。 请联系服务器管理员,webmaster@strivemedicare.in并告知他们错误发生的时间,以及可能导致错误的任何行为。 有关此错误的详细信息,请参阅服务器错误日志。 此外,尝试使用错误文档处理请求时遇到 500 内部服务器错误错误。

    • 我的laravel项目通过Commission在localhost中运行良好。现在我正试图在web主机上托管它。我在下上传我的项目,并从文件夹复制所有文件,我也编辑

    • 删除php扩展URL。//.htAccess代码 RewriteEngine on RewiteRule^dashboard$dashboard.php[L] 内部服务器错误服务器遇到内部错误或配置错误,无法完成您的请求。 请与postmaster@localhost的服务器管理员联系,通知他们此错误发生的时间,以及您在此错误发生之前执行的操作。 有关此错误的详细信息可以在服务器错误日志中获得。

    • 我一直试图在nginx上安装CakePHP,但我遇到了一个死胡同。尝试访问web根目录时,我收到一个500内部服务器错误。我在我的错误中得到了这个错误。日志: PHP消息:PHP致命错误:require():无法打开required'/var/www/html/test/vendor/autoload。php'(include_path='。:/usr/share/php:/usr/share/p

    • 我想用ajax向laravel中的控制器发送post请求。ajax请求发送两个输入参数,我希望controller在数据库中找到包含第一个参数的列,然后使用第二个输入参数设置name属性。但是我在控制台500中有这个错误消息(内部服务器错误)。 Ajax功能: 路线: 控制器功能: 而且我导入csrf无处不在,因为上次当我做AJAX调用我有这个csrf的问题,下面的代码已经修复了我的问题,但现在不