c# - Asp.NET Web API throwing 404 instead of 400 -
i have built service in .net 4.5 , entity framework 6, using asp.net web api template. when make request service , omit required parameter, returning 404 - not found, instead of 400 - bad request. tried checking see if required parameters null, it's not reaching code inside method (see code below). question how change default response or make return 400 missing required parameters. thanks!
[route("item")] [httpget] public ihttpactionresult getitem(string reqparam1, string reqparam2) { if (reqparam1 == null || reqparam2 == null) throw new httpresponseexception(httpstatuscode.badrequest); //remainder of code here }
here webapi.config file. don't think have modified default.
public static class webapiconfig { public static void register(httpconfiguration config) { // web api configuration , services // web api routes config.maphttpattributeroutes(); config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional } ); } }
just note: api isn't accessing information such item/electronics/tvs more items item green , square, descriptions mandatory pass in - query /item?color=green&shape=square.
the server returns 404 because cannot find route trying access. arguments should part of route, optionals or not: route("items/{reqparam1}/{reqparam2}")
if defined them optionals route should still called if use items
, can throw badrequest. if not optionals notfound still thrown.
you should post webapi config, can see base route mapping.
edit take following route example:
config.routes.maphttproute( name: "runswithparams", routetemplate: "api/{controller}/{project}/{skip}/{take}", defaults: new { take = routeparameter.optional, skip = routeparameter.optional } );
the project param mandatory, remaining optional. can call project, or remaining, , if use 1 of optionals 404 thrown, because route not defined. same using decorators, not solve issue, explains bit better routing. still, don't see why need badrequest in particular.
yet edit:
to use request url parameters mention @ end of post, need use [fromuri] decorator, see this page more details, , breef example follows:
// post api/files/{project}?target={target} public httpresponsemessage post(string project, string target, [fromuri]string fname){...}
Comments
Post a Comment