簡體   English   中英

C# MVC ActionResult

[英]C# MVC ActionResult

我正在學習 ASP.MVC 並遇到一個問題,不知道這是否是解決問題的方法。

我有一個具有以下操作結果的控制器:

[Route("customers/show/{id}")]
public ActionResult Show(int id)
{
    var customer = GetCustomers().SingleOrDefault(c => c.Id == id);
    return View(customer);
}

問題是只要將整數作為參數發送就沒有問題。 例如“/customers/show/123”,但是如果有人嘗試像這樣訪問“/customers/show/12xyz”,那么它會拋出一個丑陋的錯誤,如下所示:

Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Show(Int32)' in 'MyApp.Controllers.CustomersController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

我想避免該應用程序錯誤,所以我嘗試這樣解決。 這是正確的MVC方式還是有其他更聰明的方式?

[Route("customers/show/{id}")]
public ActionResult Show(string id)
{
    int custId = 0;
    int.TryParse(id, out custId);

    var customer = GetCustomers().SingleOrDefault(c => c.Id == custId);
    return View(customer);
}
[Route("customers/show/{id}")]
public ActionResult Show(int? id)
{
    var customer = GetCustomers().SingleOrDefault(c => c.Id == id);
    if (customer == null)
    {
        return HttpNotFound();
    }
    return View(customer);
}

這樣,如果數據庫/文件/無論您在何處搜索該 ID,都沒有任何內容,您將向客戶返回一個結果,讓他們知道這一點; 在這種情況下,HTTP 錯誤 404:未找到。

這實際上取決於您想如何處理這些問題。 如果有人繞過您的搜索 UI 直接進入詳細信息頁面,則您可以返回 404 未找到頁面,也可以將他們直接重定向到搜索頁面,具體取決於您的用例。

您收到此特定錯誤的原因是您對自身的路由沒有類型約束。 你真的只想處理一個int。 但是,如果您將約束放在那里並且值不是 int,那么通用 404 錯誤處理就會開始。這完全取決於您的業務需求,所以我將向您展示一些選項:

處理所有詳細信息並在未找到時重定向到搜索:

[Route("customers/show/{id}")]
public ActionResult Show(string id)
{
    if (!int.TryParse(id, out var parsedId)) {
        return Redirect("/customers");  // Or return HttpNotFound();
    }

    // Note: You should really pass your Id into GetCustomers somehow or else it'll pull 
    //everything from your database first and then find the one customer in memory
    var customer = GetCustomers().FirstOrDefault(c => c.Id == parsedId);

    if (customer == null)
    {
        return Redirect("/customers");  // Or return HttpNotFound();
    }
    return View(customer);
}

任何非整數將由通用 404 處理:

[Route("customers/show/{id:int}")]
public ActionResult Show(int? id)
{
    if (!id.HasValue) {
            return Redirect("/customers");  // Or return HttpNotFound();
    }

    var customer = GetCustomers().FirstOrDefault(c => c.Id == id.Value);
    if (customer == null)
    {
        return Redirect("/customers");  // Or return HttpNotFound();
    }
    return View(customer);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM