public HttpResponseMessage GetPerson(int id)
{
var person = personService.GetPersonById(id);
if (person == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No person with ID = {0}", id)),
ReasonPhrase = "Person ID Not Found"
};
throw new HttpResponseException(resp);
};
return Request.CreateResponse(HttpStatusCode.OK, person);
}
public HttpResponseMessage AddPerson([FromBody] PersonRequestDto personDto)
{
Person person = Mapper.Map(personDto);
var persons = personService.AddPerson(person);
return Request.CreateResponse(HttpStatusCode.OK, persons);
}
Application_Start 中完成AutoMapper注册
public class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(c =>
{
c.CreateMap().ForMember(s=>s.UserAge,d=>d.MapFrom(e=>e.Age));
});
}
}
public class RedisService where T : new()
{
public static ConfigurationOptions QueryConfig = new ConfigurationOptions
{
EndPoints =
{
{ "localhost", 6380 },
{ "localhost", 6381 },
{ "localhost", 6382 }
},
};
public static ConfigurationOptions SaveConfig = new ConfigurationOptions
{
EndPoints =
{
{ "localhost", 6379 }
},
};
public static T Get(string type,string key)
{
ConnectionMultiplexer redis =
ConnectionMultiplexer.Connect(QueryConfig);
IDatabase db = redis.GetDatabase();
string value = db.StringGet(string.Format("{0}:{1}",type,key));
return JsonConvert.DeserializeObject(value);
}
public static bool Save(string type, string key, T reqDto)
{
ConnectionMultiplexer redis =
ConnectionMultiplexer.Connect(SaveConfig);
IDatabase db = redis.GetDatabase();
string json = JsonConvert.SerializeObject(reqDto);
return db.StringSet(string.Format("{0}:{1}", type, key), json);
}
}
SimpleInjector 作为Ioc Container
public static class SimpleInjectorWebApiInitializer
{
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
}
private static void InitializeContainer(Container container)
{
container.Register();
container.Register();
}
}
public class PersonRepository : IRepository
{
public List GetAll()
{
return RedisService.Get("persons",string.Empty);
}
public Person GetById(int id)
{
return RedisService.Get("persons",id.ToString());
}
public bool Add(Person reqDto)
{
return RedisService.Save("persons", reqDto.Id.ToString(), reqDto);
}
public bool Update(Person reqDto)
{
throw new NotImplementedException();
}
public bool Remove(Person reqDto)
{
throw new NotImplementedException();
}
}