![](/img/trans.png)
[英]When adding a user to a role in asp.net mvc 4.5, i'm getting an error- “user (user name) not found”
[英]Why I'm getting a HTTP 400 (bad request) error when I'm posting user credentials with JQuery .ajax() method, to a C# controller? (ASP.NET Mvc Kestrel)
你好,所以我想在 C# 中創建一個 Kestrel web 應用程序,它根據用戶通過填寫 HTML 頁面中的輸入框提供的信息來注冊用戶。
該頁面位於名為“wwwroot”的文件夾中,該文件夾位於應用程序的根目錄中。 具有 JQuery 語法的文件內容如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="Design/registerStyle.css" />
<script src="https://code.jquery.com/jquery-3.6.1.js"
integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin="anonymous"></script>
<title>Register</title>
</head>
<body>
<form>
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="uname"><b>User Name</b></label>
<input type="text" placeholder="Enter Your User Name" name="uname" id="uname" required>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<button type="button" class="registerbtn" id="regbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? <a href="login.html">Sign in</a>.</p>
</div>
</form>
<script>
$('#regbtn').click(function () {
let user_name = $('#uname').val();
let stringified_data = JSON.stringify(user_name);
$.ajax({
url: '/session/regist',
type: 'POST',
data: stringified_data,
success: function (response) {
console.log('Success', response);
},
fail: function (failed) {
console.log('Failed', failed);
}
});
});
</script>
</body>
</html>
這不是唯一的 html 頁面...但我認為在這個問題上無關緊要。 它只是一個樣板寄存器 window。
通過注冊,我的意思是我想將這些憑據放入一個名為 database.db 的數據庫文件中,就這么簡單......這是 SQL 語法,以便您了解結構:
CREATE TABLE User (
`UserID` INTEGER PRIMARY KEY AUTOINCREMENT
, `UserName` TEXT NOT NULL
)
我只創建了兩個單元格,因為我還不想處理太多數據。 此數據庫文件位於名為 Database 的文件夾中,該文件夾位於應用程序的根目錄中。 我需要將 Sqlite 與 EntityFramework 一起使用,因為我的教授說我們不能使用 PHP 和任何其他類似的。 我正在使用“SQLite 數據庫瀏覽器”檢查數據。
所以我在一個名為 Controllers 的文件夾中創建了一個 SessionController class,該文件夾位於應用程序的根目錄中:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using System.ComponentModel;
namespace WebApplication3.Controllers
{
[ApiController]
public class SessionController : Controller
{
[HttpPost, Route("/session/regist")]
public IActionResult AddUserToDatabase([FromForm] string UserName)
{
try
{
/* Establish connection with database */
using var connection = new SqliteConnection("Data source=database.db");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = "insert into " +
"User " +
"( `UserName`) " +
"values " +
"(@username);";
/* Add parameters with value */
command.Parameters.AddWithValue("@username", UserName);
/* Execute the SQL command and close connection */
command.ExecuteNonQuery();
connection.Close();
}
catch(Exception ex) {
Console.WriteLine(ex.Message);
return Redirect("/page/registerFailed.html");
}
return Redirect("/page/registerSuccess.html");
}
}
}
這個 controller 只是一個簡單的:建立連接,創建一個 SQL 命令然后在打開的數據庫上執行它,關閉數據庫然后將用戶重定向到指定的 HTML 頁面。
好吧,我在這個文件夾中還有另一個 controller class,它叫做 HomeController:
using Microsoft.AspNetCore.Mvc;
namespace WebApplication3.Controllers
{
public class HomeController : Controller
{
[HttpGet, Route("")]
public IActionResult Login()
{
return Redirect("/page/login.html");
}
}
}
當應用程序加載時,這將重定向到登錄 HTML 頁面。
關於啟動應用程序的類...我在應用程序的根目錄中的一個單獨的 C# 文件中有一個程序和一個啟動 class。 程序 class:
using Starting.Start;
namespace Starting.Prog
{
public class Program
{
/* Builds and runs the app with the help of the HostBoulder methods */
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
/* Builds the application using the Startup class */
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(web_builder =>
{
web_builder.UseStartup<Startup>();
});
}
}
這個 class 構建應用程序,然后在中間件所在的 Startup class 的幫助下運行它。 啟動 class:
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.FileProviders;
namespace Starting.Start
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddMvcOptions(options =>
{
options.RespectBrowserAcceptHeader= true;
options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
}
/* Configure the app middleware */
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
/* Gets the root directory */
string root_directory = Directory.GetCurrentDirectory();
/* Gets the directory where the html files are located */
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(root_directory, "wwwroot")),
RequestPath = "/page"
});
/* Enables routing */
app.UseRouting();
/* Specifying the endpoints */
app.UseEndpoints(endpoints =>
{
/* Starter page (login.html) */
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Login}"
);
/* Create the route for the registration method */
endpoints.MapControllerRoute(
name: "Session",
pattern: "/session/regist",
defaults: new { controller = "Session", action = "AddUserToDatabase" }
);
});
}
}
}
有了這個啟動頁面加載(又名 login.html )。
問題是,當我單擊調用 JQuery.ajax() 方法的 register.html 上的注冊按鈕時,我收到 HTTP 400(錯誤請求)錯誤。 請參見下面的屏幕截圖:
所以我首先嘗試傳遞用戶在 ajax 方法中輸入的基本值(我沒有對輸入數據進行字符串化),然后......我得到了同樣的錯誤。 然后我在 SessionController class 中的 AddUserToDatabase 方法上面指定了一個屬性標記,它告訴它消耗什么類型的數據:
[HttpPost, Route("/session/regist"), Consumes("application/json")]
public IActionResult AddUserToDatabase([FromForm] string UserName)
{
Here is the user registration....
}
這給了我一個不同的錯誤...不支持的媒體類型(HTTP 415 錯誤)。 接下來我做的......我在 ajax 方法中指定了數據和內容類型,只是在方法末尾添加:
dataType: "json",
contentType: "application/json"
再次出現同樣的錯誤。
在此之后我被卡住了,我不知道從這一點開始在 web 上移動到哪里,或者我應該做什么。
能否請您告訴我應該聲明或做出不同的哪些內容,並提供一些提示或資源來告訴我我做錯了什么? 提前致謝!
只需更改您發布的數據格式,如下所示:
$('#regbtn').click(function () {
let user_name = $('#uname').val();
let stringified_data = { UserName: user_name }; //change here....
$.ajax({
url: '/session/regist',
type: 'POST',
data: stringified_data,
success: function (response) {
console.log('Success', response);
},
fail: function (failed) {
console.log('Failed', failed);
}
});
});
后端代碼應如下所示:
[HttpPost, Route("/session/regist")]
public IActionResult AddUserToDatabase([FromForm] string UserName)
{
//...
}
順便說一句,Ajax 無法處理服務器端重定向,您需要在ajax.success()
function 中使用window.location.href
,如下所示:
$.ajax({
url: '/session/regist',
type: 'POST',
data: stringified_data,
success: function (response) {
window.location.href = response.url; //add here...
},
fail: function (failed) {
console.log('Failed', failed);
}
});
后端代碼應如下所示:
[HttpPost, Route("/session/regist")]
public IActionResult AddUserToDatabase([FromForm] string UserName)
{
//....
return Json(new { url= "/page/registerSuccess.html" });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.