Ema.H
Ema.H

Reputation: 2878

Why Request is null in my controller?

I call a a methode by HttpPost in my ServiceController from my View http://localhost/Case/Form

My serviceController class:

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

[...]

And i call him in my MailHelper.cs :

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

But an exception occure because Request is null...

So, my Question is, why Request is null ? Is it assigned only in the current view controller, so here in my CaseController only ?

Upvotes: 1

Views: 5338

Answers (1)

Palin Revno
Palin Revno

Reputation: 586

You are creating a new controller, that is not associated with a request. Instead of putting the get domain in a controller and then creating a new one, You can just access the current request via the HttpContext.Current.Request. This is also available in a static method.

Upvotes: 2

Related Questions