6

My task is to create services (using asp.net api) and use it for android aplication.

I have never done anything like this so I have a problems at begining. :(

First I created Class Library with few classes. Second I created asp.net web application and refered class library into it.

My first problem is that I dont know how to access to methode from controller. So, I tried to just start without it, to see does it even work... When I runned it I added controller to the path but I get error.

I runner it like this: http://localhost:51041/ValuesController1

Error is this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could >have been removed, had its name changed, or is temporarily unavailable. Please review the >following URL and make sure that it is spelled correctly.

Requested URL: /ValuesController1

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408

Ok, now my code:

Controller class:

    public class ValuesController1 : ApiController
{
    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    public void Delete(int id)
    {
    }

    public List<BuzzMonitor.Web.Message> Search()
    {
        //return new BuzzMonitor.Web.MessageHandler.Search(...);
    }
}

MessageHandler class:

public class MessageHandler
{
    private List<Message> _dummyMessages = new List<Message>()
        {
            new Message(){
                MessageId = 1,
                CreatedDate = new DateTime(2014, 5, 27),
                Text = "Srpska vodoprivreda...",
                Autor = "Marko Markovic",
                Source = "Twitter"

            },
            new Message(){
                MessageId = 2,
                CreatedDate = new DateTime(2014, 5, 27),
                Text = "Aerodrom Beograd...",
                Autor = "Zoran Zoric",
                Source = "B92"

            }
        };

    public List<Message> GetLatestMessages(int nrMessagesToReturn)
    {
        List<Message> retVal;

        retVal = this._dummyMessages.GetRange(0, nrMessagesToReturn);

        return retVal;
    }

    public List<Message> Search(string text, DateTime dateFrom, DateTime dateTo, List<int> themeIds, List<int> sourceIds, int pageIndex, int pageSize)
    {
        List<Message> retVal;

        retVal = this.Search(text, dateFrom, dateTo, themeIds, sourceIds);

        if (retVal != null && retVal.Count > 0)
        {
            retVal = retVal.GetRange(pageIndex * pageSize, pageSize);
        }

        return retVal;
    }

    public List<Message> Search(string text, DateTime dateFrom, DateTime dateTo, List<int> themeIds, List<int> sourceIds)
    {
        List<Message> retVal = null;

        retVal = this._dummyMessages.Where(m => m.Text.IndexOf(text, StringComparison.OrdinalIgnoreCase) > -1 &&
            m.CreatedDate >= dateFrom &&
            m.CreatedDate < dateTo &&
            (themeIds == null || themeIds.Count == 0 || (themeIds.Contains(m.ThemeId))) &&
            (sourceIds == null || sourceIds.Count == 0 || (sourceIds.Contains(m.SourceId)))).ToList<Message>();

        return retVal;
    }


}

Message class:

    public class Message
{
    public int MessageId { get; set; }

    public DateTime CreatedDate { get; set; }

    public string Text { get; set; }

    public string Autor { get; set; }

    public string Source { get; set; }

    public int ThemeId { get; set; }

    public int SourceId { get; set; }
}

So, problems are: 1. I dont know how to call Search in controler from MessageHandler. 2. I get error message and I dont know is it because I dont have everythig I need in controller or I need to set some configurations...

I am using VS 2010.

Thank you for helping and sorry if my questions seems stupid...

3
  • What happens if you try http://localhost:51041/api/ValuesController1/Get Commented May 28, 2014 at 9:46
  • 1
    You should read how the routing works in Web Api it's heavily conventions based and the name of your controller and actions must follow the conventions for it to work. Commented May 28, 2014 at 9:50
  • @RobH Thank you for advice, now I am reading but I dont have App_Start and AppConfig.cs in it. Maybe because of version or something... Or do I need to create it manualy maybe? Commented May 28, 2014 at 10:41

2 Answers 2

6

Rename your controller class to XXXController. For example, in this case call it ValuesController. The default routing in WebAPI is set up with this code:

routes.MapRoute(
    "Default",                          //The name of this route.
    "api/{controller}/{action}/{id}",   //The url, note the prefix "api" is hard-coded.
    new {                               //The default values:
        controller = "Home",            //{controller} in URL defaults to Home (i.e. HomeController)
        action = "Index",               //{action} in URL defaults to Index method
        id = UrlParameter.Optional });  //The id part is optional

An example URL based on the above route is /api/Home/action/id. Note that the Controller suffix of the class is not used. So to map this to your renamed ValuesController it becomes:

http://localhost:51041/api/Values/Get
Sign up to request clarification or add additional context in comments.

6 Comments

I did this but I still have problems, i think that I need to configurate it somehow, but I dont know what to do. I am using VS 2010, and in project I dont have App_Start and WebAPiConfig in it :/
What is in your Application_Start method in the Global.asax.cs file?
That's odd, sounds like you have a partial template. Try adding in the default route in Application_Start like this: GlobalConfiguration.Configuration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
I added this. I just saw you edited your post, I dont know where I need to add routhes.MapRoute(...). Sorry for so many stupid questions, but I'm kinda lost laa... :/
with just this code: Application_Start like this: GlobalConfiguration.Configuration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }); I don't have error 404 anymore!! THANK YOU SO MUCH!
|
3

I think you may need to change ValuesController1 to ValuesController

and use

http://localhost:51041/api/Values

3 Comments

still same :/ this didn't help.
@MalaAiko, how you configured routing?
I didn't do anything particular :( I will read about it now and try! I never did this before so it's confusing for me :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.