2

How I can read parameter value from controller constructor in asp.net web API 2 ??

 public class DataController : ApiController
{
    private APIMgr apiMgr ; // APIMgr custome class 

    public DataController()
    {
       // var id = Request.GetRouteData(); = 5 // this parameter must send with alla request "http://localhost/TAPI/api/data/5"
        apiMgr= new apiMgr(id);
    }
Osama AbuSitta
  • 3,918
  • 4
  • 35
  • 51

3 Answers3

3

The HttpContext is not set when the controller class is constructed , but it set ("injected") later by the ControllerBuilder class .
According to this I can to access the HttpContext by override "Initialize" method . This page explains ASP.NET MVC request flow

  protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
    }
Osama AbuSitta
  • 3,918
  • 4
  • 35
  • 51
1

You cannot read route parameters from within a constructor...only from an action method. You'll need to define an appropriate route with expected templates. Take a look at the default controller in your route config in WebApiConfig.cs

Also HttpContext is not accessible from within a controller constructor.

Spencer
  • 251
  • 2
  • 8
  • thanx @Spencer , I want to execute this line before any action. – Osama AbuSitta Aug 06 '15 at 12:41
  • Depends what you want to do here.... if you want to execute something before you hit the Action method you could create an ActionFilterAttribute and decorate your controller OR Action method with it. Then you can access HttpActionContext and therefore the HttpRequest. – Spencer Aug 06 '15 at 12:49
  • What are you trying to achieve? – Spencer Aug 06 '15 at 12:57
  • I am try to check the token [from my windows App] that send with every http request to ensuring the http requests from my app – Osama AbuSitta Aug 06 '15 at 13:02
  • In that case I would suggest an ActionFilter. I do something similar in my API's to ensure a custom http header is present in the request. Example: http://stackoverflow.com/questions/10307333/asp-net-web-api-actionfilter-example – Spencer Aug 06 '15 at 13:14
  • Thanks a lot,I will try this – Osama AbuSitta Aug 06 '15 at 13:32
0

You can't. To read parameter values in action methods there are a few ways. Let us assume a model that represents a person.

public class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now let us assume that we with to have an API method that enables us to send a representation of a person to the server that will then save it to some data store. For this purpose we implement a POST method that accepts parameters to build our person object. There are a few ways we could do this.

Method 1: Bind parameters from the request body

public IHttpActionResult Post([FromBody]Person person)
{
    // validate your parameter in some way
    if (person.Equals(default(Person))) return BadRequest("person must not be null");
    // go off and save the person
    var createdPerson = myPersonRepository.Save(person);
    if (createdPerson == default(Person)) return InternalServerError();
    return CreatedAtRoute("DefaultApi", new { id = createdPerson.Id }, createPerson);
}

This requires you to pass a JSON representation of your person in the request body. Something like the following should do it.

{
    "firstname": "Luke",
    "lastname": "Skywalker"
}

Method 2: Bind parameters from the request URL query string

public IHttpActionResult Post([FromUri]Person person)
{
    // validate your parameter in some way
    if (person.Equals(default(Person))) return BadRequest("person must not be null");
    // go off and save the person
    var createdPerson = myPersonRepository.Save(person);
    if (createdPerson == default(Person)) return InternalServerError();
    return CreatedAtRoute("DefaultApi", new { id = createdPerson.Id }, createPerson);
}

This requires you to pass the parameter values in the query string, for example:

http://mywhizzyapi/api/people?firstname=luke&lastname=skywalker

Method 3: Explicitly pass parameters and create the object yourself

public IHttpActionResult Post(string firstname, string lastname)
{
    // validate your parameter in some way
    if (id.Equals(Guid.Empty)) return BadRequest("id must not be null or an empty GUID");
    if (string.IsNullOrEmpty(firstname)) return BadRequest("firstname must not be null or empty");
    if (string.IsNullOrEmpty(lastname)) return BadRequest("lastname must not be null or empty");
    // create your person object
    var person = New Person {
        id = id,
        firstName = firstname,
        lastname = lastname,
    };
    // go off and save the person
    var createdPerson = myPersonRepository.Save(person);
    if (createdPerson == default(Person)) return InternalServerError();
    return CreatedAtRoute("DefaultApi", new { id = createdPerson.Id }, createPerson);
}

This method also requires you to pass the parameter values in the query string, for example:

http://mywhizzyapi/api/people?firstname=luke&lastname=skywalker

But in the last case as mentioned you have to bind the parameters explicitly to your model.

ceej
  • 1,863
  • 1
  • 15
  • 24