Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将信息保存在数据库中,然后使用.NET内核将请求发布到外部API_C#_Asp.net Mvc_Api_Asp.net Core_.net Core - Fatal编程技术网

C# 将信息保存在数据库中,然后使用.NET内核将请求发布到外部API

C# 将信息保存在数据库中,然后使用.NET内核将请求发布到外部API,c#,asp.net-mvc,api,asp.net-core,.net-core,C#,Asp.net Mvc,Api,Asp.net Core,.net Core,我不熟悉.NETCore,我正在尝试使用.NETCore应用程序MVC体系结构处理外部API。作为一个新手,我真的很难理解MVC的根本原因,我自己做了研究,了解了很多事情。现在我有两个问题(第一个是关于如何开始的建议,第二个是关于我到目前为止所做的工作) 问题1(建议) 所以正如我所说的,我正在尝试使用MVC架构调用外部API。我想做的是假设管理员是第一次登录,第一个用户名和密码分别是默认的“admin”和“myadminpassword”。要登录,管理员必须提供一个新密码,该密码作为请求主体发

我不熟悉.NETCore,我正在尝试使用.NETCore应用程序MVC体系结构处理外部API。作为一个新手,我真的很难理解MVC的根本原因,我自己做了研究,了解了很多事情。现在我有两个问题(第一个是关于如何开始的建议,第二个是关于我到目前为止所做的工作)

问题1(建议) 所以正如我所说的,我正在尝试使用MVC架构调用外部API。我想做的是假设管理员是第一次登录,第一个用户名和密码分别是默认的“admin”和“myadminpassword”。要登录,管理员必须提供一个新密码,该密码作为请求主体发送到API。现在,我希望将新密码保存到我的数据库中,然后从那里保存到API端点。这可行吗?这是个好主意吗

问题2(到目前为止的方法)

因此,从下面的大量教程中获得帮助是我迄今为止所做的工作

Main\u应用程序/区域/Application/View/Home/Index.cshtml

@using (Html.BeginForm("Login", "WhAuth", FormMethod.Post))
{
    <label>
        Username:
        <input type="text" placeholder="admin" readonly />
    </label>
    <br />
    <label>
        Password:
        <input type="text" placeholder="*****" readonly />
    </label>
    <br />
    <label>
        Enter New Password:
        @Html.TextAreaFor(m => m.New_password, 5,5,new { })
    </label>
    <br />
    <button class="btn btn-default" type="submit">Sign up as Admin</button>
}
主要应用程序/模型/DB/whapp.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace PTCConnector.Areas.Whatsapp.Models
{
    public class AdminLoginModel
    {
        public string Df_username = "admin";
        public string Df_password = "anySecretPassword";
        [Required(ErrorMessage = "New Password Is Required")]
        public string New_password { get; set; }

    }
}
public class whapp : BaseEntity
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string New_Password { get; set; }
    public string Token { get; set; }
    public string WhatsappId { get; set; } //Whatsapp ID
    public string type { get; set; }
    public string recipient_type { get; set; }
    public string Messagebody { get; set; }
    public string URL { get; set; }
    public string Group_id { get; set; }
    public string Caption { get; set; }
    public string Media_Id { get; set; }
    public string Status { get; set; }
    public string GroupName { get; set; }
}
public DbSet<whapp> whapp { get; set; }
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PTCConnector.Areas.Whatsapp.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace PTCConnector.Areas.Whatsapp.Controllers
{
    [Area("Whatsapp")]
    [TypeFilter(typeof(AdminActionFilter))]
    [Authorize(Roles = "Admin")]
    public class WhAuthController : Controller
    {
        public AdminLoginModel whLogin = new AdminLoginModel();

        public async Task Login()
        {
            HttpClientHandler clientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
            };
            var client = new HttpClient(clientHandler);

            byte[] bytes = Encoding.UTF8.GetBytes($"{whLogin.Df_username}:{whLogin.Df_password}");

            var Base64Credentials = Convert.ToBase64String(bytes);

            System.Diagnostics.Debug.WriteLine(Base64Credentials);

            // Set Base64Credentials as Authorization header with Prefix 
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Base64Credentials);

            // Just some data for POST, change freely!
            var data = new Dictionary<string, string>
            {
                { "new_password", $"{whLogin.New_password}" } //
            };
            System.Diagnostics.Debug.WriteLine(data.Values);
            Console.WriteLine("here 1");
            // Encode the data in FORM URL Data
            var content = new FormUrlEncodedContent(data);



            // Make Async Post Call with Client. Parameters are URL and Data to POST!
            var response = await client.PostAsync("https://localhost:9090/v1/users/login", content);

            // Async!! - Read the response content as String
            var responseString = await response.Content.ReadAsStringAsync();

            // Print out the Response String for Debugging!
            //Console.WriteLine(responseString);

            System.Diagnostics.Debug.WriteLine(responseString);
            System.Diagnostics.Debug.WriteLine("Check");
            Console.WriteLine("CheckNow");
        }
    }
}
 services.AddDbContext<ApplicationDbContext> ... //

            services.AddHttpClient("WhappClient", client =>
            {
                client.BaseAddress = new Uri("https://localhost:9090/v1/users/login");
                client.DefaultRequestHeaders.Add("username", "admin");
                client.DefaultRequestHeaders.Add("password", "anySecretPassword");
            });
Main\u应用程序/Data/ApplicationDBContext.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace PTCConnector.Areas.Whatsapp.Models
{
    public class AdminLoginModel
    {
        public string Df_username = "admin";
        public string Df_password = "anySecretPassword";
        [Required(ErrorMessage = "New Password Is Required")]
        public string New_password { get; set; }

    }
}
public class whapp : BaseEntity
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string New_Password { get; set; }
    public string Token { get; set; }
    public string WhatsappId { get; set; } //Whatsapp ID
    public string type { get; set; }
    public string recipient_type { get; set; }
    public string Messagebody { get; set; }
    public string URL { get; set; }
    public string Group_id { get; set; }
    public string Caption { get; set; }
    public string Media_Id { get; set; }
    public string Status { get; set; }
    public string GroupName { get; set; }
}
public DbSet<whapp> whapp { get; set; }
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PTCConnector.Areas.Whatsapp.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace PTCConnector.Areas.Whatsapp.Controllers
{
    [Area("Whatsapp")]
    [TypeFilter(typeof(AdminActionFilter))]
    [Authorize(Roles = "Admin")]
    public class WhAuthController : Controller
    {
        public AdminLoginModel whLogin = new AdminLoginModel();

        public async Task Login()
        {
            HttpClientHandler clientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
            };
            var client = new HttpClient(clientHandler);

            byte[] bytes = Encoding.UTF8.GetBytes($"{whLogin.Df_username}:{whLogin.Df_password}");

            var Base64Credentials = Convert.ToBase64String(bytes);

            System.Diagnostics.Debug.WriteLine(Base64Credentials);

            // Set Base64Credentials as Authorization header with Prefix 
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Base64Credentials);

            // Just some data for POST, change freely!
            var data = new Dictionary<string, string>
            {
                { "new_password", $"{whLogin.New_password}" } //
            };
            System.Diagnostics.Debug.WriteLine(data.Values);
            Console.WriteLine("here 1");
            // Encode the data in FORM URL Data
            var content = new FormUrlEncodedContent(data);



            // Make Async Post Call with Client. Parameters are URL and Data to POST!
            var response = await client.PostAsync("https://localhost:9090/v1/users/login", content);

            // Async!! - Read the response content as String
            var responseString = await response.Content.ReadAsStringAsync();

            // Print out the Response String for Debugging!
            //Console.WriteLine(responseString);

            System.Diagnostics.Debug.WriteLine(responseString);
            System.Diagnostics.Debug.WriteLine("Check");
            Console.WriteLine("CheckNow");
        }
    }
}
 services.AddDbContext<ApplicationDbContext> ... //

            services.AddHttpClient("WhappClient", client =>
            {
                client.BaseAddress = new Uri("https://localhost:9090/v1/users/login");
                client.DefaultRequestHeaders.Add("username", "admin");
                client.DefaultRequestHeaders.Add("password", "anySecretPassword");
            });
然后将其命中到所述的特定端点
wait client.PostAsync(“https://localhost:9090/v1/users/login“,内容)

返回将是一个令牌,我希望将其保存在数据库中以备将来端点调用,此外,给定的新密码也将以哈希格式保存在我的数据库中。

开始回答,因为我还不能简单地进行注释。你能提供一些关于你在这里想要完成什么的更多信息和背景吗?外部API的用途是什么,因为它似乎是另一个本地项目?我们正在研究的项目是MVC项目还是WebAPI项目?用户存储是本地的还是使用外部身份提供程序

到目前为止,您已经接收了一些输入数据,将其编码为Base64字符串,然后将其发送到其他本地API。您提到的数据库保存在哪里?此外,如果您要将密码存储在数据库中,请确保在保存密码之前采取适当的步骤对其进行哈希和盐处理。老实说,如果需要用户/身份验证框架,您应该只使用内置的ASP.NET标识。正如其他人评论的那样,你在哪里挂断了电话,出了什么问题


我希望这听起来不像是在问所有的问题,哈哈!我相信如果我们能得到更多的背景和细节,我们可以提供更多的帮助。如果你能提供一些信息,我可以编辑我的答案,希望能提供更多帮助。

到底是什么问题?您是否正在尝试将数据保存到数据库中并收到错误?您应该使用依赖项注入注册DbContext,并在
appsettings.json
文件下定义数据库连接字符串。@iamdlm我想由管理员/用户填写表单,当用户输入新密码并提交时,我想将新密码保存在我的数据库中,同时返回一个作为令牌的响应在这种情况下,我想将该令牌保存到我的数据库中,以便将其用于其他端点。问题是,您在哪里跌倒?你试过什么?什么不起作用?你的问题太宽泛了。如果您还没有找到解决方案,尝试一下,然后用遇到的具体问题更新您的问题。如果您遇到任何异常,请将其与完整堆栈跟踪一起发布。谢谢您的评论。实际上,我正在开发一个在docker容器上运行的应用程序,我正在努力达到最终目标。由于我刚刚接触.netcore MVC,我花了一些时间才了解了基本知识。你可以看到我的下一个评论,也许会更清楚。我将编辑question@FarrukhAhmedKhan不确定您是否仍然需要帮助,但问题是如何将其保存到数据库中?你说在你的问题中一切都很好,所以只是想知道在哪里可以提供帮助。如果您只需要保存到数据库,请查看Microsofts文档上的Entity Framework Core,您需要设置一个DbContext,然后使用依赖项注入将其注入。