API Versioning in .NET Core - AssumeDefaultVersionWhenUnspecified - asp.net-core

I'm looking into adding versioning to an existing API we have. We are embedding the version in the URL.
The requirement for the versioning is that it should be easy to add a new version, but not everything changes and we don't want to go through all controllers and add new version attributes when we get a new version. Is there any way to tell Microsoft.AspNetCore.Mvc.Versioning that a particular method should be available regardless of versions?
I have tried decorating my method with both with the version:apiVersion and with just a basic route.
[Route("v{version:apiVersion}/customers/{customerId}/estates/{estateId:int}/meters/{meterNumber}-{installationId}/consumption/detail")
[Route("customers/{customerId}/estates/{estateId:int}/meters/{meterNumber}-{installationId}/consumption/detail")]
My configuration is as such (the version number 3 is just for testing purposes):
services.AddApiVersioning(config =>
{
config.DefaultApiVersion = new ApiVersion(3, 0);
config.AssumeDefaultVersionWhenUnspecified = true;
config.ReportApiVersions = true;
});
When calling the endpoint with this configuration I get "The HTTP resource that matches the request URI 'http://{{host}}/api/customers/{customer}/estates/{estate}/meters/{meter}-{installation}/consumption/detail' is not supported
As soon as I add the [ApiVersion("3.0")] attribute everything works. But my thought was that if I currently run on version 2, but changes to other parts of the API warrant a new version and the default version of the API, I don't want to have to go this controller and "bump" the version. It should just continue to respond, unless I specify something specific.
If I change the AssumeDefaultVersionWhenUnspecified to false, I get an "An API version is required, but was not specified." But I expected that it would just grab the route without the version?
I have read about the limitations here: https://github.com/Microsoft/aspnet-api-versioning/wiki/Known-Limitations#url-path-segment-routing-with-a-default-api-version
But it doesn't seem to work.

Setting AssumeDefaultVersionWhenUnspecified = true is a highly abused feature. This is only meant to facilitate backward compatibility. Once you opt into API Versioning, all API controllers have some implicit or explicit API version. Assuming a version provides a mechanism to handle the "original", unnamed version that would otherwise break existing clients that don't know to include an API version in requests.
"Is there any way to tell Microsoft.AspNetCore.Mvc.Versioning that a particular method should be available regardless of versions?"
Yes, but I'm not entirely sure that is what you're looking for. An API can be version-neutral, which means it will accept any and all API versions, including none at all. This is useful for certain types of APIs such as a /ping health check or DELETE, which typically do not change over time. Such an API can be decorated with [ApiVersionNeutral]. This can be for all APIs on a controller or a specific action. Note that once you choose this path, "there can be only one."
There is not a complete picture of your setup. It appears that you are adding API versioning to an existing set of APIs. One of the primary purposes of DefaultApiVersion is to set what the default API version should be when no other information is available. If you applied no API versions whatsoever - for example, using attributes, then this would be the implicit API version of all APIs. This prevents you from having to retrofit all of your existing controllers and code. What's less obvious is that once you apply any explicit API version, then the implicit rule is ignored. This ensures that implicit versions can be sunset. The default version often does not matter. It's simply a way for you to indicate what the initial API version originally was. It's most relevant when grandfathering in existing APIs.
Given your configuration:
// implicitly 3.0 because DefaultApiVersion = 3.0 and there
// are no explicit versions from attributes or conventions
[Route("customers/{customerId}/estates/{estateId:int}/meters/{meterNumber}-{installationId}/consumption/detail")]
public class CustomerController : ControllerBase
{
}
Grandfathered controller with implicit versioning
// explicitly 2.0 due to attributes; DefaultApiVersion is ignored
[ApiVersion("2.0")]
[Route("v{version:apiVersion}/customers/{customerId}/estates/{estateId:int}/meters/{meterNumber}-{installationId}/consumption/detail")
[Route("customers/{customerId}/estates/{estateId:int}/meters/{meterNumber}-{installationId}/consumption/detail")]
public class CustomerController : ControllerBase
{
}
Controller with explicit versioning
With the exception of supporting the backward compatible, original API version, all APIs versions are explicit and discrete; this is by design. Fuzzy matching will not work in a predictable way so it's important to have exact matches.
You seem to be describing API version interleaving - e.g. multiple API versions implemented on a single controller implementation. I presume it might look like:
[ApiVersion("2.0")]
[ApiVersion("3.0")]
[Route("v{version:apiVersion}/customers/{customerId}/estates/{estateId:int}/meters/{meterNumber}-{installationId}/consumption/detail")
[Route("customers/{customerId}/estates/{estateId:int}/meters/{meterNumber}-{installationId}/consumption/detail")]
public class CustomerController : ControllerBase
{
// implicitly maps to 2.0 from the controller, but does not
// match 3.0 because there is an explicit 3.0 mapping
[HttpGet]
public IActionResult Get(
string customerId,
int estateId,
string meterNumber,
string installationId ) => Ok();
// explicitly maps to 3.0 only
[MapToApiVersion("3.0")]
[HttpGet]
public IActionResult GetV3(
string customerId,
int estateId,
string meterNumber,
string installationId ) => Ok();
// explicitly maps to 3.0 only
// a 2.0 request produces 405
[MapToApiVersion("3.0")]
[HttpPut]
public IActionResult Put(
string customerId,
int estateId,
string meterNumber,
string installationId
[FromBody] ComsumptionDetail detail ) => Ok();
}
Controller with version interleaving
The DefaultApiVersion can only apply a single, implicit API version. This means that no interleaving with it can ever occur. Once you start explicitly adding versions, you must also start including the implicit version because there is no other way to indicate that the implicit version should no longer be matched.
In terms of route definitions and API version mapping, there are several methods that can be used to minimize code churn. The VersionByNamespaceConvention is a built-in convention you can apply which will derive an API version from the .NET namespace of the controller type. This can make it really easy to add, remove, and organize controllers with their API versions. They can also use interleaving because the mapping is additive, but that may be confusing to maintain. You can define your own conventions as well.
Double-route registration is a consequence of versioning by URL segment. It is the least RESTful method of versioning because it violates the Uniform Interface constraint. No other method of versioning has this issue. I advise against floating the default route and API version mapping because you are very likely to break clients at some point. If you're only using double-routes for backward compatibility of your original API version, then you should be fine. When you eventually create new controllers for future API versions, you'll only have one route with the API version in the template.

Related

Is there an issue with the custom object JSON serialization implementation of System.IdentityModel.Tokens.Jwt for .Net 6?

We migrated from .Net Core (dotnet core) 3.1 to .Net 6. We were using the System.IdentityModel.Tokens.Jwt to create a payload and generate a security token with that payload.
Our application has yet to be migrated from Newtonsoft.Json to System.Text.Json due to a lot of nonstandard property serialization that is currently favoring the former. The custom claim value contains an object that was previously serialized properly by adhering to the camelCase contract resolver that was specified in the Startup.cs configuration with regards to JSON serialization.
We upgraded from version 5.5.0 of System.IdentityModel.Tokens.Jwt to version 6.16.0 and the serialization is behaving differently.
We are using a mixture of IdentityModel well-known claims along with a custom claim. The custom claim is the only one that is an object and also the only one behaving this way. All other claims are primitive types and are written to the token as specified and expected.
This is an example of the code that is not working:
var payload = new JwtPayload()
{
{JwtRegisteredClaimNames.Iss, issuer},
{JwtRegisteredClaimNames.Iat, now},
{JwtRegisteredClaimNames.Nbf, now},
{JwtRegisteredClaimNames.Exp, exp},
{JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")},
{"role", user.UserType},
{"customClaim", customClaimObjectInstance }
};
var jwt = new JwtSecurityToken(_jwtHeader, payload);
/* Token below contains a valid base64 encoded JWT Token with
the customClaim property containing pascal values that match
the properties of the C# Poco object and not at all following
either default convention or even any JsonProperty description
attributes such as [JsonProperty("name")] that may decorate each
property of the custom object */
var token = _jwtSecurityTokenHandler.WriteToken(jwt);
My first hunch was such that it may be related to a conflict with default library of System.Text.Json. I proceeded to troubleshoot by adding the [JsonPropertyName("name")] attribute to some of the properties but did not succeed. I expected that if System.Text.Json was being used that at least those description attributes would be respected or consulted during the serialization of the claim object.
I also tried serializing the value with Newtonsoft JsonConverter.Serialize function and use the serialized value as the value of the claim key-value-pair. However, the stringified object quotes were escaped and found plenty of escaping characters ("****") all over the value which was undesired.
After some time searching online and trying to come up with the right keywords to search google and GitHub and I finally got to what I, for now, consider a workaround and not a long-term solution.
The clue was provided by this open issue on Github. I simply, to my interpretation, forced the use of the Newtonsoft serializing and deserializing delegates by specifying the following lines before instantiation of payload variable posted in the question:
JsonExtensions.Serializer = JsonConvert.SerializeObject;
JsonExtensions.Deserializer = JsonConvert.DeserializeObject;
This was the first indication of potentially System.Text.Json being forced from deep within a library. It may also be an indication that the time has come to prioritize the migration to System.Text.Json from Newtonsoft.Json.
I hope this workaround helps somebody else get to this short-term patch, and not spend as much as I did.
If I find anymore concrete ideas or clues about this matter, I will update this answer.
The code below works
/* This was the key to achieving the prior result, however
temporary it may be. */
JsonExtensions.Serializer = JsonConvert.SerializeObject;
JsonExtensions.Deserializer = JsonConvert.DeserializeObject;
var payload = new JwtPayload()
{
{JwtRegisteredClaimNames.Iss, issuer},
{JwtRegisteredClaimNames.Iat, now},
{JwtRegisteredClaimNames.Nbf, now},
{JwtRegisteredClaimNames.Exp, exp},
{JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")},
{"role", user.UserType},
{ "customClaim", customClaimObjectInstance}
};
var jwt = new JwtSecurityToken(_jwtHeader, payload);
var token = _jwtSecurityTokenHandler.WriteToken(jwt);
I am thankful for the issue on github, but more importantly to the solution suggested here.

API Versioning in dotnet core

I am working on APIs in dotnet core 2.2 and I'd like to version my API.
I'm looking for some solutions except:
Routing method (api/v1/controller, api/v2/contoller)
Routing method using APIVersioning package, (api/v{version: apiVersion}/contoller})
I want to know if there is any other solutions in which I don't have to change the route attribute? I might be completely wrong but can I use middleware? Like, map delegate to map the the incoming requests (based on v1, v2 it carries) to its right controller?
I'll highly appreciate any feedback and suggestions.
You can use the APIVersioning package and configure it so it selects the version based on the HTTP Header.
services.AddApiVersioning(c =>
{
c.ApiVersionReader = new HeaderApiVersionReader("api-version");
}
And then you can use the [ApiVersion] attribute on your controllers.
Can you use custom middleware - yes; however, be advised that endpoint selection is typically much more involved. The routing system provides extension and customization points, which is exactly what API Versioning does for you. Creating your own versioning solution will be a lot more involved than having to add a route template parameter.
If you're going to version by URL segment, then API Versioning requires that you use the ApiVersionRouteConstraint. The default name is registered as apiVersion, but you can change it via ApiVersioningOptions.RouteConstraintName. The route parameter name itself is user-defined. You can use whatever name you want, but version is common and clear in meaning.
Why is a route constraint required at all? API Versioning needs to resolve an API version from the request, but it has no knowledge or understanding of your route templates. For example, how would ASP.NET know that the route parameter id in values/{id:int} has be an integer without the int constraint? Short answer - it doesn't. The API version works the same way. You can compose the route template however you want and API versioning knows how and where to extract the value using the route constraint. What API versioning absolutely does not do is magic string parsing. This is a very intentional design decision. There is no attempt made by API Versioning to try and auto-magically extract or parse the API version value from the request URL. It's also important to note that the v prefix is very common for URL segment versioning, but it's not part of the API version. The approach of using a route constraint negates the need for API Versioning to worry about a v prefix. You can include it in your route template as a literal, if you want to.
If the issue or concern is having to repeatedly include the API version constraint in your route templates, it really isn't any different than including the api/ prefix in every template (which I presume you are doing). It is fairly easy to remain DRY by using one of the following, which could include the prefix api/v{version:apiVersion} for all API routes:
Extend the RouteAttribute and prepend all templates with the prefix; this is the simplest
Roll your own attribute and implement IRouteTemplateProvider
Ultimately, this requirement is yet another consequence of versioning by URL segment, which is why I don't recommend it. URL segment versioning is the least RESTful of all versioning methods (if you care about that) because it violates the Uniform Interface constraint. All other out-of-the-box supported versioning methods do not have this issue.
For clarity, the out-of-the-box supported methods are:
By query string (default)
By header
By media type (most RESTful)
By URL segment
Composition of n methods (ex: query string + header)
You can also create your own method by implementing the IApiVersionReader.
Attributes are just one way that API versions can be applied. In other words, you don't have to use the [ApiVersion] attribute if you don't want to. You can also use the conventions fluent API or create your own IControllerConvention. The VersionByNamespaceConvention is an example of such a convention that derives the API version from the containing .NET namespace. The methods by which you can create and map your own conventions are nearly limitless.

IAuthenticationFilter equivalent in MVC6

I'm moving a Web Api 2 project to MVC 6, since Microsoft is merging the two APIs in ASP.NET 5. In my WebApi project I had a custom Attribute Filter class that would authenticate, authorize and prevent transaction replays using a combination of public key, private key and HMAC authentication (basically, doing this with some tweaks to fit into my project).
Now in MVC6, as far as I understand I must stop using anything in the Microsoft.Web.Http namespace and instead use Microsoft.AspNet.Mvc. So I have done that, but the Microsoft.AspNet.Mvc.Filters doesn't seem to have any equivalent of Web Api 2's IAuthenticationFilter.
This is a problem for me because my customer AuthenticationFilter implemented all of IAuthenticationFilter, with all the logic in there. More importantly, it was using the Context to temporarily store the public key of the account, so my controller could access it to load up the account in turn.
So my question is, what is the proper way to filter requests in MVC6, using an Authentication Filter-like class to intercept the requests and return the appropriate status codes? I can't find any article that goes specifically in these details (they all tend to cover MVC5).
I know it's an older question, but hopefully someone (maybe even yourself) might find value in the answer.
MVC6 does in fact have an alternative. You have an
public abstract class AuthorizationFilterAttribute :
Attribute, IAsyncAuthorizationFilter, IAuthorizationFilter, IOrderedFilter
which basically tells you, that you can create your custom class, derive it from this (namespace of all of these interfaces, btw, is Microsoft.AspNet.Mvc.Filters and that should be it. You can either decorate the action with it, or you can do this in Startup.cs, to apply to all actions:
public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container.
services.AddMvc(options =>
{
// add an instance of the filter, like we used to do it
options.Filters.Add(new MySpecialFilter());
});
services.AddTransient<LogFilter>();
}
If you want to use a bit more logic in the filter (e.g. my LogFilter above) which is instantiated through DI, you need to use either Service Filters or Type Filters.
You can now decorate the actions with [ServiceFilter(typeof(LogFilter))] or use o.Filters.Add(new ServiceFilterAttribute(typeof(LogFilter))); in the Startup.cs file. But keep in mind, to do this you need to register the type with the DI container, like I did above with the .AddTransient<>() call.
IAuthenticationFilter is no more and IAuthorizationFilter simply does not replace it in MVC 6
Reason: authentication is NOT EQUAL to authorization.
Therefore IMO the authentication filter should stay available!

Authentication on dynamically added route

There are an option in ServiceStack to add routes dynamically, using IAppHost.Routes.Add. This is quite handy as it allows reusable services to be packed in a form of plugin and attached to actual applications.
To illustrate, here's an excerpt of application host configuration that enables a plugin and attaches routes:
class AppHost: AppHostHttpListenerBase {
public override void Configure(Container container) {
// other stuff
Plugins.Add(new MyReusablePlugin());
Routes.Add(typeof(string), "/stuff", "GET");
Routes.Add(typeof(string), "/other-stuff", "POST");
}
}
The problem is, I can't find a way to specify that authentication is required for those dynamically added routes. As of ServiceStack 4.0.15 there are no overload to Routes.Add that allow specifying that those routes require authentication. Is it possible (maybe in newer versions)?
Ideally, such a mechanism should support specifying roles/permissions, just like RequiredRoleAttribue or RequiresAnyRoleAttribute.
One more thing: I'm aware of Global request filters and it looks like they are a bit too global to be a valid solution here, but I might be wrong. If it's possible to achieve the same result (including ability to specify required roles/permissions) using request filters I would be glad to accept an example of such apporach as an answer.
You can do this using the AddAttributes extension method provided on Type:
typeof(YourType).AddAttributes(new RequiredRoleAttribute("Admin"));
So you would need to do this in addition to the Routes.Add method.

Searching with WebAPI

I have made a web API class for my Customer model. I have the standard methods (GET, POST, PUT, DELETE). The problem is, I want to implement another GET method which is a search. Something like this:
[HttpGet]
public IEnumerable<Customer> Search(string id)
{
var customers = customerRepository.Search(id);
return customers;
}
The search method performs a search based on the account number of my customers, using the .Contains() method.
The problem is, when I navigate to: mySite.com/api/Customers/Search/123 I get a 404. What am I doing wrong here?
While Darin's answers are always of top quality this question would actually benefit from an answer that explains how searching, paging and filtering should actually be done in any API and how it should be done using the most current version of Web API (v2).
This is a post which I consider a good resource on the matter (technology indenpendent):
http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
The answer should also reflect what's new in ASP.NET Web API v2 because Darin's answer is quite old.
Since this question comes up at the top when doing Google search for "asp.net web api searching" I will try to explain few things here.
To get as close as possible to REST principles with the latest version of ASP.NET Web API (v2) one should take a serious look at attribute routing that was introduced in the latest version. It is very hard to achieve RESTful routing with the old, classic, convention based routing (in global.asax.cs or RouteConfig.cs).
You should read more about that here
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
Now, to go into details how to implement the specifics you ask about.
The most common practice is to expose these types of functionality through query string parameters.
Per REST principles, you should have one endpoint for your Customers resource, for instance
/api/customers
To achieve this you would decorate your GetCustomers() action in your Web API controller like this
[HttpGet]
[Route("/api/customers")]
public HttpResponseMessage GetCustomers(string q="", string sortBy="", string sortDirection="", bool active=true, ...)
{
// q = being optional search query
// sortBy = optional sort by column/property
// sortDirection = optional sort direction
// active = filter on 'active' column/property
// ... other filters may be applicable
}
You would implement this action closely to what you did in classic MVC if you wanted to provide filtered Views.
I would only introduce new controllers and custom actions if really needed, for some custom edge cases.
with regards to a comment about SearchFilter strongly typed object, let's explain that this won't work out of the box because the default model binder will not bind to this class when using GET requests.
So I'd either take those properties out of SearchFilter class and put them on the action itself so they'd bind via query string binder or use the [FromBody] binder if you wanted to bind from the request body. As per http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
HTH
As per the default route setup only the standard controller action names are allowed (the RESTful ones and the dispatching is done based on the HTTP verb). If you want to violate the RESTful conventions and use some custom action names then you will have to modify your route setup in order to include the action name in the url: api/{controller}/{action}/{id}. Now you can send a request to /api/Customers/Search/123 which will invoke the Search action on the Customers API controller.