normandantzig
normandantzig

Reputation: 169

ASP.NET Syntax and conventions

I am reading Designing Evolvable Web APIs with ASP.NET. In one of the exercises, the book has me edit a Controller using Visual Studio. This is being done in ASP.NET using C#. The template I used was the standard ASP.NET web application API.

I have edited the controller to the way the book shows (although it does not seem to give very specific directions). Here is what my controller looks like.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using WebApplication4.Models;
using WebApplication4.Providers;
using WebApplication4.Results;

namespace WebApplication4.Controllers
{
    public class GreetingController : ApiController
    {
           public string GetGreeting() {
            return "Hello World!";
            }

    }
    public static List<Greeting> _greetings = new List<Greeting>();
    public HttpResponseMessage PostGreeting(Greeting greeting)
    {
        _greetings.Add(greeting);
        var greetingLocation = new Uri(this.Request.RequestUri, "greeting/" + greeting.Name);
        var response = this.Request.CreateResponse(HttpStatusCodeResult.Created);
        response.Headers.Location = greetingLocation;
        return response;

    }
}

I get errors on:

Upvotes: 2

Views: 10222

Answers (2)

Carlos Aguilar Mares
Carlos Aguilar Mares

Reputation: 13581

Your _greetings field needs to be part of the class, as well as the PostGreeting method, it seems you just closed "}" of the class a bit early. MOve the "}" before the _greetings field to the end of the file, like:

namespace WebApplication4.Controllers
{
    public class GreetingController : ApiController
    {
           public string GetGreeting() {
            return "Hello World!";
            }

    public static List<Greeting> _greetings = new List<Greeting>();
    public HttpResponseMessage PostGreeting(Greeting greeting)
    {
        _greetings.Add(greeting);
        var greetingLocation = new Uri(this.Request.RequestUri, "greeting/" + greeting.Name);
        var response = this.Request.CreateResponse(HttpStatusCodeResult.Created);
        response.Headers.Location = greetingLocation;
        return response;

    }
}  
}

Upvotes: 2

SLaks
SLaks

Reputation: 887305

As the error is trying to tell you, your fields and methods must be inside the class.
Check your braces.

Upvotes: 14

Related Questions