Suppose we have an application for a multi-user blog. Each user of the application may have several blogs hosted by the service.
Our API allows you to read and write blog posts. In some cases, specifying BlogId is optional, for example, receiving all posts tagged using ASP.NET:
/api/posts?tags=aspnet
If we wanted to see all posts tagged with ASP.NET on a particular blog, we could request:
/api/posts?blogId=10&tags=aspnet
Some API methods require a valid BlogId, for example, when creating a new blog post:
POST: /api/posts
{
"blogid" : "10",
"title" : "This is a blog post."
}
BlogId , , () . , ( , ).
IAccountContext, . .
{
bool ValidateBlogId(int blogId);
string GetDefaultBlog();
}
ASP.NET Web API, :
- BlogId , uri, , . 400, .
- BlogID , BlogDd
IAccountContext . , , IAccountContext .
[Update]
Twitter @Aliostad Blog Uri ( ), ..
GET api/blog/1/posts -- get all posts for blog 1
PUT api/blog/1/posts/5 -- update post 5 in blog 1
Post id ( ).
BlogID. , Uri, @alexanderb . ActionFilter:
public class ValidateBlogAttribute : ActionFilterAttribute
{
public IBlogValidator Validator { get; set; }
public ValidateBlogAttribute()
{
Validator = new FakeBlogValidator();
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
var blogId = actionContext.ActionArguments["blogId"] as int?;
if (blogId.HasValue && !Validator.IsValidBlog(blogId.Value))
{
var message = new HttpResponseMessage(HttpStatusCode.BadRequest);
message.ReasonPhrase = "Blog {0} does not belong to you.".FormatWith(blogId);
throw new HttpResponseException(message);
}
base.OnActionExecuting(actionContext);
}
}
public class FakeBlogValidator : IBlogValidator
{
public bool IsValidBlog(int blogId)
{
return blogId != 999;
}
}
blogId / [ValidateBlog].
, @alexanderb , .