Victor
Victor

Reputation: 555

How to create WCF WebApi in standard ASP.NET

I want use WCF WebApi in a regular ASP.NET C# project. Already I have created WCF WebApi in MVC application but I want to create in normal ASP.NET. Are there any sample links to show this?

Upvotes: 1

Views: 950

Answers (1)

Alexander Zeitler
Alexander Zeitler

Reputation: 13089

File / New Project / ASP.NET Application

NuGet: Install-Package WebApi.All

Add a new ContactsResource

[ServiceContract]
public class ContactsResource {
    [WebGet(UriTemplate = "")] 
    public List<Contact> Get() {
        return new List<Contact>()
                {
                    new Contact()
                        {
                            Name = "Alex"
                        }
                };
     }
}

Add a Contact class

public class Contact {
    public string Name { get; set; }
}

Edit the Global.asax.cs

Modify Application_Start:

void Application_Start(object sender, EventArgs e) {
    // Code that runs on application startup
    RouteTable.Routes.MapServiceRoute<ContactsResource>("contacts");
}

Hit F5 and navigate to http://mywebsite/contacts

Done.

<ArrayOfContact>
    <Contact>
        <Name>Alex</Name>
    </Contact>
 </ArrayOfContact>

Upvotes: 5

Related Questions