为什么我的控制器中的请求为空?

时间:2013-09-06 08:37:33

标签: c# asp.net-mvc-4

我从我的http://localhost/Case/Form

我的ServiceController中通过HttpPost调用一个方法

我的serviceController类:

using System.Web;
using System.Web.Mvc;
[...]

namespace ApnNephro.WebUI.Controllers
{
    public class ServicesController : Controller
    {
        public string GetDomain()
        {
            string url = "";
            try
            {
                string _url = Request.Url.AbsolutePath;
                int _si = (_url.IndexOf("//"));
                int _fi = (_url.Substring(_si + 2)).IndexOf("/"); // first /
                url = _url.Substring(0, _fi + _si + 2);
                return url.ToString();
            }
            catch (InvalidOperationException ioe)
            {
                throw new Exception(ioe.Message + " / " + ioe.StackTrace);
            }
            catch (Exception e)
            {    
                throw new Exception(e.Message + " / " + e.StackTrace);
            }
            return url.ToString();
        }

[...]

我在MailHelper.cs中打电话给他:

private static string domain = new ServicesController().GetDomain();

但是因为Request为null而发生异常......

所以,我的问题是,为什么Request为空? 它是仅在当前视图控制器中分配的,所以这里仅在我的CaseController中吗?

1 个答案:

答案 0 :(得分:0)

您正在创建一个与请求无关的新控制器。 而不是将get域放在控制器中然后创建一个新域, 您只需通过HttpContext.Current.Request访问当前请求即可。 这也可以通过静态方法获得。

相关问题