Search code examples
c#rest.net-4.0httpwebresponseself-host-webapi

Returning a HttpWebResponse from a Server Application (REST)


Im tring to set the values of the HttpWebResponse that is returned by the Controller but I can't create an HttpWebResponse object.

Right now I just want to set the status code but maybe I'll need other parts of the HttpWebResponseclass soon too. All I can do by now is returning strings as a status what is obviously wrong since Get methods already return other Data.

This is my controller(just a test application to understand how a REST server&client are implemented and how they communicate):

public class TeamsController : ApiController
{
    public static List<Team> teams = new List<Team>() 
    {
        new Team  { Kuerzel = "BVB09",Name="Borrusia Dortmund", Stadt="Dortmund"},
        new Team  { Kuerzel = "RWE",Name="Rot Weiss Essen", Stadt="Essen"}
    };

    public IEnumerable<Team> GetAllTeams()
    {
        Console.WriteLine("All teams returned");
        return teams;
    }

    public Team GetTeamById(int id)
    {
        if (id < teams.Count)
        {
            Console.WriteLine("Team with ID=" + id + " returned");
            return teams[id];
        }
        else
            return null;
    }

    public string PostNewTeam(Team team)
    {
        teams.Add(team);
        Console.WriteLine("Post Team: " + team.ToString());
        return "Success";
    }

}

Solution

  • use using System.Net.Http; and add return Request.CreateResponse(HttpStatusCode.OK, "success"); during PostNewItem() method return; Return type of the Post() method should be HttpResponseMessage