c# - Validate content-length before model binding ASP.NET Web Api -
i wondering how can validate content-length before request body read model binder in asp.net web api.
i can in action it's waste of resources because stream has been read?
var contentlength = request.content.headers.contentlength; if (contentlength > 1024*1024*20) { throw new httpresponseexception(httpstatuscode.requestentitytoolarge); } is ok in action filter?
if using owin hosting api, , want globally apply restriction requests, make check in simple owin middleware executed before web api in owin pipeline:
app.use(async (c, n) => { var request = c.request; if (request != null) { string[] headervalues; if (request.headers.trygetvalue("content-length", out headervalues)) { var lengthvalue = headervalues.first(); if (convert.toint64(lengthvalue) > 1024 * 1024 * 20) { c.response.statuscode = (int)httpstatuscode.requestentitytoolarge; return; } } } await n.invoke(); }); //app.usewebapi(..) [edit]
if need restrict content-length in more fine graded fashion, best option create authorizationfilter executed before model binding in web api pipeline, opposed generic actionfilter.
something should work:
public class maxcontentlengthattribute : authorizationfilterattribute { private readonly long _maxcontenttype; public maxcontentlengthattribute(long maxcontenttype) { _maxcontenttype = maxcontenttype; } public override void onauthorization(httpactioncontext actioncontext) { var contentlength = actioncontext.request.content.headers.contentlength; if (contentlength.hasvalue && contentlength.value > _maxcontenttype) { actioncontext.response = actioncontext.request.createresponse(httpstatuscode.requestentitytoolarge); } } } and in controller:
[maxcontentlength(1024*1024*20)] public void post([frombody]foo value) { dowork(value); } this way can respond request before content read model-binder.
Comments
Post a Comment