Reputation: 12794
We have a Desktop Client and a REST API. For several POST REST calls, we want to pass a correlation GUID from the Client to the API that is used to correlate log entries related to the same user interaction.
This parameter is optional and must be backwards compatible, not failing if it is omitted. What options are there to pass this in while keeping code clean?
I'm concerned that if I put it:
For example, an existing method is:
[HttpPost]
public HttpResponseMessage SaveData([FromBody]DataModel model)
{
...
}
I feel like I've missed something. Where is the best place for it?
Upvotes: 0
Views: 1055
Reputation: 1399
You can pass the correlation GUID from URL as optional parameter so that it will be backward compatible, clean and will not pollute your data models. For example:
[HttpPost]
[Route("api/Contact/{correlationId:Guid?}")]
public HttpResponseMessage SaveData([FromBody]DataModel model, [FromUri] Guid? correlationId = null)
{
//code to handle request
}
From MSDN:
You can make a URI parameter optional by adding a question mark to the route parameter. If a route parameter is optional, you must define a default value for the method parameter.
More information here
Hope it helps.
Upvotes: 1
Reputation: 975
It's strongly depends on your api action
either is Get
or Post
, if you using Get action you can put your parameter in header and also you can use default value for your parameter in route
configuration like this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { **id = RouteParameter.Optional** }
);
If you are using Post
action you can easily use default value in method prototype :
Example :
[HttpPost]
public object DoSomething(int logEntryIndex=0)
{
return "Something";
}
But I'm strongly recommend you always use an object as your parameter. Then it's so easy to add any property [as a new parameter] to class and you never would had these kind of problems
[HttpPost]
public object DoSomething(MyParam parameter)
{
return "Something";
}
public class MyParam
{
// prop1
// prop2
}
Upvotes: 1