从使用 Request["name"] 变量的其他控制器调用方法

call method from other controller that uses Request["name"] variable

我正在使用 Asp.net MVC。我的 HTML 代码是:

<form action="/MobilesController/SaveMobilesAd">
      <input type="text" name="brand" />
      <input type="text" name="color" />
      <!-- other stuff -->
      <input type="submit" />
</form>

brand,color这样的属性有10多个,我要在15个不同的页面上输入数据。为了避免代码冗余,我创建了一个函数 MyAd() 在这个函数中实现了我所有的逻辑,我只是​​在需要的地方调用这个函数。

public class AdController: Controller
    {
         public void MyAd()
         {
              string brand = Request["brand"];
              string color = Request["color"];
              //other stuff. take data from Request variables and save in database.
         }
    }

现在要在另一个控制器中使用 MyAd():

public class MobilesController:Controller
{
     AdController ad = new AdContoller();
     public ActionResult SaveMobilesAd()
     {
           //some stuff.
           ad.MyAd();
     }
}

现在的问题是当我在另一个控制器中调用 MyAd() 时出现异常

Object reference not set to an instance of an object

Request["brand"] 上。我怎样才能避免这个异常或者有其他方法可以实现这个?

当您调用 AdController ad = new AdContoller(); 时,Request 对象或实例不会被共享。 MobilesController 中的 Request 对象不同于 AdController 中的对象。您可以执行以下操作:

public void MyAd(HttpRequestBase externalRequest = null)
{
    HttpRequestBase currentRequest = externalRequest ?? Request;

    string brand = currentRequest ["brand"];
    string color = currentRequest ["color"];
    //...
}

然后您可以通过传递另一个 Controller 实例的 Request 来调用它(如果需要,即如果不从 AdController 调用):

public class MobilesController: Controller
{
    AdController ad = new AdContoller();
    public ActionResult SaveMobilesAd()
    {
       //some stuff.
       ad.MyAd(Request);
    }
}

话虽如此,我对这种方法不太满意。在我看来,你可以(应该?)重构它并制作一个通用的静态方法,例如,一个 Dictionary<string, string> 甚至一个自定义 class,并处理数据。