chungtinhlakho
chungtinhlakho

Reputation: 930

c# .net access parent obj

I am using .net c# MVC controller to query database for many of my projects. Every time i create a new controller, I find myself having to rewrite some of the same function for the new controller hence, I thought about writing a basic controller to handle some of the basic task that I use in all my controller (e.g., run a query and run json).

In my controller, I reference the basic controller like this.

namespace myWebAPI.Controllers
{
    public class esrcController : Controller
    {
        //
        // GET: /esrc/
        string db = "esrc-";
        basicController BasicController = new basicController();


        public string test()
        {
            return "test" + Request.ServerVariables["HTTP_REFERER"];
        }
        public string getCodingException()
        {

            return @"{""data"":" + BasicController.getDataNconvertToJSON(
                "select * from z_codingexception order by nc_key",
                BasicController.getEnviroment(db)) + "}";
        }
    }
}

in my BasicController, the getEnviroment looks at the url to determine the environment hence I need access to :

Request.ServerVariables["HTTP_REFERER"] and Request.ServerVariables["HTTP_HOST"].ToString().ToLower();

but Request is null in this controller, I only have access to request in the main controller. How do I reference httpRequest from basic controller?

Upvotes: 0

Views: 93

Answers (2)

Cam Bruce
Cam Bruce

Reputation: 5689

Just because you instantiate a new instance of a controller, doesn't mean you'll have access to the context.

One option is to create an abstract base controller that all of your other controlers would inherhit from. You'll then have access to the specific objects like Request

WebApiConfig.cs

 config.MapHttpAttributeRoutes();

Your Controller

public abstract class MyBaseController : Controller
{
 protected void myMethod()
 {
  // you have access to Request here
 }
}

public class MyController : MyBaseController
{
    [HttpGet]
    [Route("my/getstuff")]
    public IHttpActionResult GetStuff() 
    {
       // do stuff
       base.myMethod();
       return Ok();
    }
}

Upvotes: 3

Matt Spinks
Matt Spinks

Reputation: 6700

Create an action filter and add it as an attribute to that class. Within the action filter yuo wil have access to the Request object. If you override the OnActionExecuting function, the functionality in your filter will be executed before your controller.

Create a custom filter

public class CustomAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      //DO STUFF WITH YOUR REQUEST OBJECT HERE..
    }
}

Add the filter as an attribute to your controller

[CustomAttribute]
public class esrcController : Controller

Upvotes: -1

Related Questions