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);
    }
1
  • Put some of you code here and let us know what you have tried so far. Commented Aug 6, 2015 at 11:43

3 Answers 3

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

thanx @Spencer , I want to execute this line before any action.
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.
What are you trying to achieve?
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
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: stackoverflow.com/questions/10307333/…
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.