You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中无前端JS,用C#调用RestAPI登录及跳转方案

Hey there! Let's break down how to fix your login flow step by step, following ASP.NET MVC best practices and your requirements of no JavaScript use.

Step 1: Split Models for Input and API Response

Your existing Login_Model is designed to capture the API's return data, but you need a separate model to handle the login form inputs (uemail and upwd). This separation keeps responsibilities clear and avoids cluttering a single model with unrelated properties:

namespace test.Models
{
    // Model to receive login form inputs from the view
    public class LoginInputModel
    {
        public string uemail { get; set; }
        public string upwd { get; set; }
    }

    // Keep your original model for mapping API responses
    public class Login_Model
    {
        public string email { get; set; }
        public string name { get; set; }
        public Product[] products { get; set; }
        public string result { get; set; }
        public string message { get; set; }
    }

    public class Product
    {
        public string billingcycle { get; set; }
        public string nextduedate { get; set; }
        public int pid { get; set; }
        public string product_name { get; set; }
        public string product_package { get; set; }
        public string regdate { get; set; }
        public string status { get; set; }
        public string username { get; set; }
    }
}
Step 2: Update the Login View to Use Server-Side Form Submission

Modify your Index view to wrap inputs in a <form> tag, set correct name attributes (matching LoginInputModel properties), and use a submit button. We'll also add an error display area for login failures:

@{ ViewData["Title"] = "Login Page"; }
<div class="text-center">
    <form asp-action="Index" method="post">
        <label>Email Address</label>
        <input type="email" name="uemail" id="txtemail" placeholder="Enter your email" required />
        <br/>
        <label>Password</label>
        <input type="password" name="upwd" id="txtpass" placeholder="Enter your password" required />
        <br/>
        
        <!-- Display error messages if login fails -->
        @if (!string.IsNullOrEmpty(ViewData["LoginError"]?.ToString()))
        {
            <p class="text-danger">@ViewData["LoginError"]</p>
        }
        
        <button type="submit" id="btnLogin">Login</button>
    </form>
</div>

The required attribute adds basic client-side validation, and the form will submit directly to the POST version of your Index action without any JavaScript.

Step 3: Refactor the Controller's POST Action

Update the POST method to handle form inputs, call the REST API, and manage redirects or error feedback:

[HttpPost]
public IActionResult Index(LoginInputModel loginInput)
{
    // First, validate form inputs
    if (!ModelState.IsValid)
    {
        return View();
    }

    // Initialize RestSharp client and request
    client = new RestClient(baseUrl);
    Request = new RestRequest("login.php", Method.POST);

    // Add the required API parameters
    Request.AddParameter("uemail", loginInput.uemail);
    Request.AddParameter("upwd", loginInput.upwd);

    // Execute request and auto-deserialize response to Login_Model
    var response = client.Execute<Login_Model>(Request);

    if (response.IsSuccessful && response.Data != null)
    {
        if (response.Data.result.Equals("success", StringComparison.OrdinalIgnoreCase))
        {
            // Store user data temporarily for the next view (optional)
            TempData["UserDetails"] = response.Data;
            // Redirect to Privacy on successful login
            return RedirectToAction("Privacy");
        }
        else
        {
            // Pass API's error message to the view
            ViewData["LoginError"] = response.Data.message ?? "Login failed. Please check your credentials.";
        }
    }
    else
    {
        // Handle API connection failures
        ViewData["LoginError"] = "Could not connect to the login service. Please try again later.";
    }

    // Return to login view with error feedback
    return View();
}

Key improvements here:

  • Validates form inputs before making the API call
  • Uses RestSharp's generic Execute<T> method to automatically map the JSON response to your Login_Model
  • Covers edge cases like API connection failures and invalid credentials
  • Uses TempData to pass user data to the Privacy view (if you need to display user-specific content there)
Step 4: Optional - Secure the Privacy View

To ensure only logged-in users can access the Privacy view, add a check in the Privacy action:

public IActionResult Privacy()
{
    var userData = TempData["UserDetails"] as Login_Model;
    if (userData == null)
    {
        // Redirect unauthenticated users back to login
        return RedirectToAction("Index");
    }
    // Pass user data to the view if needed
    return View(userData);
}

You can then display user information in the Privacy view:

@{ ViewData["Title"] = "Privacy Policy"; }
<h1>Welcome, @Model.name!</h1>

@if (Model.products != null && Model.products.Length > 0)
{
    <h3>Your Products:</h3>
    <ul>
        @foreach (var product in Model.products)
        {
            <li>@product.product_name (Status: @product.status)</li>
        }
    </ul>
}

Why This Is the Optimal Solution

  • Separation of Concerns: Splitting input and response models keeps your code clean and maintainable
  • No JavaScript: Relies entirely on ASP.NET MVC's server-side form handling, meeting your requirement
  • Robust Error Handling: Provides clear feedback for all failure scenarios
  • Type Safety: Auto-deserialization of API responses eliminates manual JSON parsing errors

内容的提问来源于stack exchange,提问作者Muhammad Hamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:22:38