public class Product { public int ProductId { get; set; } public string ProductName { get; set; } public int PersonId { get; set; } }
public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; }
public virtual ICollection<Product> Products { get; set; } }
private MVC4WebApiContext db = new MVC4WebApiContext();
// GET api/Persons
public IEnumerable<Person> GetPeople()
{
return db.People.AsEnumerable();
}
public class MVC4WebApiContext : DbContext
{
public MVC4WebApiContext() : base("name=MVC4WebApiContext")
{
}
public DbSet<Person> People { get; set; }
public DbSet<Product> Products { get; set; }
}
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
[HttpGet]
[ActionName("Beer")]
// GET api/Products/Beer public IEnumerable<Product> GetProducts() { return db.Products.AsEnumerable().Where(x => x.productName == "Beer"); }
public HttpResponseMessage PostProduct([FromUri] int id){}
public HttpResponseMessage PostProduct([FromBody] Product product){}
public Product GetProduct([ModelBinder(typeof(CustomModelBinder))]string id){}
public class CustomModelBinder : IModelBinder
{
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
ValueProviderResult val = bindingContext.ValueProvider.GetValue(
bindingContext.ModelName);
if (val == null)
{
return false;
}
string newVal = "Hello!";
bindingContext.Model = newVal;
return true;
}
}
public class CustomActionFilter : ActionFilterAttribute { public override void OnActionExecuted(
HttpActionExecutedContext actionExecutedContext){} public override void OnActionExecuting(
HttpActionContextactionContext){}
}
[CustomActionFilter] public class ProductsController : ApiController {}
PM> Enable-Migrations -EnableAutomaticMigrations -Force
PM> Update-Database