简体   繁体   English

C# MVC ActionResult

[英]C# MVC ActionResult

I am learning ASP.MVC and stuck on a issue and dont know whether this is the way to solve the issue.我正在学习 ASP.MVC 并遇到一个问题,不知道这是否是解决问题的方法。

I have a controller with the following actionresult:我有一个具有以下操作结果的控制器:

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

The issue is as long as the integer is being sent as parameter then no problem.问题是只要将整数作为参数发送就没有问题。 For example "/customers/show/123", but If someone try to access like this "/customers/show/12xyz" then it will throw an ugly error like this:例如“/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

I want to avoid that application error so I tried solving like this.我想避免该应用程序错误,所以我尝试这样解决。 Is this the correct MVC way or is there any other smarter way?这是正确的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);
}

This way, if there is nothing in the database/file/wherever you're searching for that ID, you return a result to the customer that lets them know this;这样,如果数据库/文件/无论您在何处搜索该 ID,都没有任何内容,您将向客户返回一个结果,让他们知道这一点; in this case, an HTTP Error 404: Not Found.在这种情况下,HTTP 错误 404:未找到。

It really depends on how you want to handle those problems.这实际上取决于您想如何处理这些问题。 If someone is going directly to a detail page by bypassing your searching UI, then you can either return a 404 not found page or you could redirect them directly to the search page, depending on your use case.如果有人绕过您的搜索 UI 直接进入详细信息页面,则您可以返回 404 未找到页面,也可以将他们直接重定向到搜索页面,具体取决于您的用例。

The reason why you are getting this particular error is that you don't have a type constraint on the route it self.您收到此特定错误的原因是您对自身的路由没有类型约束。 You really only want to deal with an int.你真的只想处理一个int。 However, if you put that constraint on there and the value isn't an int, then the generic 404 error handling is going to kick in. It all depends on what your business requirements are here, so I'll show you a few options:但是,如果您将约束放在那里并且值不是 int,那么通用 404 错误处理就会开始。这完全取决于您的业务需求,所以我将向您展示一些选项:

Handle all details and redirect to search when not found:处理所有详细信息并在未找到时重定向到搜索:

[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);
}

Any non-int will be handled by the generic 404:任何非整数将由通用 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