I've got have the following controller:
[Route("xapi/statements")] << -- NOTICE THE ROUTE
[Produces("application/json")]
public class StatementsController : ApiControllerBase
With he following actions
/// <summary>
/// Stores a single Statement with the given id.
/// </summary>
/// <param name="statementId"></param>
/// <param name="statement"></param>
/// <returns></returns>
[AcceptVerbs("PUT", "POST", Order = 1)]
public async Task<IActionResult> PutStatement([FromQuery]Guid statementId, [ModelBinder(typeof(StatementPutModelBinder))]Statement statement)
{
await _mediator.Send(PutStatementCommand.Create(statementId, statement));
return NoContent();
}
/// <summary>
/// Create statement(s) with attachment(s)
/// </summary>
/// <param name="model"></param>
/// <returns>Array of Statement id(s) (UUID) in the same order as the corresponding stored Statements.</returns>
[HttpPost(Order = 2)]
[Produces("application/json")]
public async Task<ActionResult<ICollection<Guid>>> PostStatements(StatementsPostModelBinder model)
{
ICollection<Guid> guids = await _mediator.Send(CreateStatementsCommand.Create(model.Statements));
return Ok(guids);
}
The actions are executed in the following order:
1. PutStatement
2. PostStatements
But PutStatement should only be triggered if the statementId parameter is provided. This is not the case.
I'm using 2 model binders to parse the content of the streams as either application/json or multipart/form-data if the statements have any attachments.
1. StatementPutModelBinder
2. StatementsPostModelBinder
How do i prevent the action from being excuted if the statementId parameter is not provided?
Eg. /xapi/statements/ => Hits PutStatement
I did not find a answer for my own question, but i made a mistake and was under the impression that the xAPI statements resource should allow statementId as a parameter for POST requests. Therefore i do not have the issue any more, which started my question.
Related
I'm trying to update task details:
var t = await graphClient.Planner.Tasks[task.Id].Details.Request().GetAsync();
var ETag = t.GetETag();
However GetETag() returns null.
The ETag is part of the AdditionalData dictionary, so I can extract it writing my own method.
For example:
var e = etag = (taskDetails.AdditionalData["#odata.etag"] as JsonElement?)?.GetString();
But why does the built-in method not work? My code is almost exactly the same as Microsoft's test code.
Thanks.
Please debug and check GetEtag() method that is exposed here. Also validate the entity passed onto this method is not null.
namespace Microsoft.Graph
{
using System;
/// <summary>
/// Helper class to extract #odata.etag property and to specify If-Match headers for requests.
/// </summary>
public static class EtagHelper
{
/// <summary>
/// Name of the OData etag property.
/// </summary>
public const string ODataEtagPropertyName = "#odata.etag";
/// <summary>
/// Returns the etag of an entity.
/// </summary>
/// <param name="entity">The entity that contains an etag.</param>
/// <returns>Etag value if present, null otherwise.</returns>
public static string GetEtag(this Entity entity)
{
if (entity == null)
{
throw new ArgumentNullException(nameof(entity));
}
entity.AdditionalData.TryGetValue(ODataEtagPropertyName, out object etag);
return etag as string;
}
}
}
I am using Swashbuckle to generate my API definitions in a .NET 5 project.
To add a summary and remarks to my documentation, I am currently putting a comment on some of my actions like this:
/// <summary>
/// CreateSite
/// </summary>
/// <remarks>
/// Options:
/// * Enterprise = 0,
/// * Site = 1
/// * Order = 2
/// * Line = 3
/// * Product = 4
///
/// </remarks>
[HttpPost]
[Route("sites")]
public async Task<IActionResult> CreateSiteAsync([FromBody] SiteCreateRequest createRequest)
{ // My controller stuff }
This generates a nice documentation and is very helpful.
Howevery, my "summary" field has always the same value like my controller action name - I already put efford in a very good naming of the actions:
You can see above that the summary contains "CreateSite" and my controller name is "CreateSiteAsync".
Is there a way to automatize this?
So could I set some option in the service to use the controller name as a "default" summary option used in the json file?
Then I can just avoid this cumbersome comments in the all simple requests without the need of any docu.
I also use Swashbuckle and to properly document my APIs I use Swagger tags. Attached is an example of my actual use. For your specific controller name tag, in my example it would be [SwaggerOperation("In-Transit Shipments")]
/// <summary>
/// In-transit shipments
/// </summary>
/// <remarks>
/// Get in-transit shipments for a client
/// </remarks>
/// <returns></returns>
[SwaggerTag("GroundTransportation")]
[SwaggerOperation("In-Transit Shipments")]
[SwaggerResponse(200, typeof(List<LoadSummaryDto>), Description = "OK")]
[SwaggerResponse(400, typeof(ErrorMessageDto), Description = "Bad Request")]
[SwaggerResponse(404, typeof(ErrorMessageDto), Description = "Not Found")]
[SwaggerOperationProcessor(typeof(ReDocCodeSampleAppender), "Curl,CSharp,Java")]
[HttpGet("ShipmentInformation/In-Transit")]
[TraceAction(message: "Controller: Retrieving in-transit shipments for client", level: LogLevel.Information, externalErrorMessage: "In-transit shipments could not be found")]
public async Task<IActionResult> GetClientInTransitShipments(uint? page = GroundTransportationConstants.DefaultPage, uint? pageSize = GroundTransportationConstants.DefaultPageSize)
{
// ... a bunch of api code :-)
}
I have an Action that consumes application/x-www-form-urlencoded:
[HttpPost("~/connect/token"), Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> Exchange([FromBody]OpenIdConnectRequest request)
{
..
}
But Swashbuckle generates empty array for Consumes property. If I change it to application/json, consumes array is generated properly.
Is it a bug related to application/x-www-form-urlencoded or I need to configure Swashbuckle additionally to support this application type?
That 'consumes' is not catered for out-of-the-box for Swashbuckle, a custom extension is required like the ones in this part of #domaindrivendev's GitHub project
There are three steps:
Create Parameter Attribute
Create Extension
Add instruction to Swashbuckle to process the new extension
Add an attribute to the parameter in an Controller method
I'll add more instructions in my fork of the repo, but here is the code:
1. FromFormDataBodyAttribute.cs
using System;
using System.Collections.Generic;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Validation;
/// <summary>
/// FromFormDataBody Attribute
/// This attribute is used on action parameters to indicate
/// they come only from the content body of the incoming HttpRequestMessage.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public sealed class FromFormDataBodyAttribute : ParameterBindingAttribute
{
/// <summary>
/// GetBinding
/// </summary>
/// <param name="parameter">HttpParameterDescriptor</param>
/// <returns>HttpParameterBinding</returns>
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
{
if (parameter == null)
throw new ArgumentNullException("parameter");
IEnumerable<MediaTypeFormatter> formatters = parameter.Configuration.Formatters;
IBodyModelValidator validator = parameter.Configuration.Services.GetBodyModelValidator();
return parameter.BindWithFormatter(formatters, validator);
}
}
2 AddUrlFormDataParams.cs
using Swashbuckle.Swagger;
using System.Linq;
using System.Web.Http.Description;
/// <summary>
/// Add UrlEncoded form data support for Controller Actions that have FromFormDataBody attribute in a parameter
/// usage: c.OperationFilter<AddUrlFormDataParams>();
/// </summary>
public class AddUrlFormDataParams : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var fromBodyAttributes = apiDescription.ActionDescriptor.GetParameters()
.Where(param => param.GetCustomAttributes<FromFormDataBodyAttribute>().Any())
.ToArray();
if (fromBodyAttributes.Any())
operation.consumes.Add("application/x-www-form-urlencoded");
foreach (var headerParam in fromBodyAttributes)
{
if (operation.parameters != null)
{
// Select the capitalized parameter names
var parameter = operation.parameters.Where(p => p.name == headerParam.ParameterName).FirstOrDefault();
if (parameter != null)
{
parameter.#in = "formData";//NB. ONLY for this 'complex' object example, as it will be passed as body JSON.
//TODO add logic to change to "query" for string/int etc. as they are passed via query string.
}
}
}
}
}
3 Update Swagger.config
//Add UrlEncoded form data support for Controller Actions that have FromBody attribute in a parameter
c.OperationFilter<AddUrlFormDataParams>();
4. Add an attribute to the parameter in an Controller method
[FromFormDataBody]OpenIdConnectRequest request
I am developing an application and I started to use as my base some code from an example by John Papa. Looking on the web I found this same code and it appears in an answer to a question on
Stackoverflow. Here is the question:
How to de-attach an entity from a Context in Entity Framework?
It's in the answer that was given by: SynerCoder
One part of the answer suggests the following class that is used to provide a repository from a dictionary of cached repositories. Can someone help me out and tell me is there really
an advantage in doing this. I understand the code but can't see the point of keeping repositories in a dictionary. Would it not be the case that every new web request would see an
empty dictionary and have to get / make a new repository anyway.
Data/Helpers/IRepositoryProvider.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using Data.Contracts;
namespace Data.Helpers
{
/// <summary>
/// A maker of Repositories.
/// </summary>
/// <remarks>
/// An instance of this class contains repository factory functions for different types.
/// Each factory function takes an EF <see cref="DbContext"/> and returns
/// a repository bound to that DbContext.
/// <para>
/// Designed to be a "Singleton", configured at web application start with
/// all of the factory functions needed to create any type of repository.
/// Should be thread-safe to use because it is configured at app start,
/// before any request for a factory, and should be immutable thereafter.
/// </para>
/// </remarks>
public class RepositoryFactories
{
/// <summary>
/// Return the runtime repository factory functions,
/// each one is a factory for a repository of a particular type.
/// </summary>
/// <remarks>
/// MODIFY THIS METHOD TO ADD CUSTOM FACTORY FUNCTIONS
/// </remarks>
private IDictionary<Type, Func<DbContext, object>> GetFactories()
{
return new Dictionary<Type, Func<DbContext, object>>
{
//If you have an custom implementation of an IRepository<T>
//{typeof(IArticleRepository), dbContext => new ArticleRepository(dbContext)}
};
}
/// <summary>
/// Constructor that initializes with runtime repository factories
/// </summary>
public RepositoryFactories()
{
_repositoryFactories = GetFactories();
}
/// <summary>
/// Constructor that initializes with an arbitrary collection of factories
/// </summary>
/// <param name="factories">
/// The repository factory functions for this instance.
/// </param>
/// <remarks>
/// This ctor is primarily useful for testing this class
/// </remarks>
public RepositoryFactories(IDictionary<Type, Func<DbContext, object>> factories)
{
_repositoryFactories = factories;
}
/// <summary>
/// Get the repository factory function for the type.
/// </summary>
/// <typeparam name="T">Type serving as the repository factory lookup key.</typeparam>
/// <returns>The repository function if found, else null.</returns>
/// <remarks>
/// The type parameter, T, is typically the repository type
/// but could be any type (e.g., an entity type)
/// </remarks>
public Func<DbContext, object> GetRepositoryFactory<T>()
{
Func<DbContext, object> factory;
_repositoryFactories.TryGetValue(typeof(T), out factory);
return factory;
}
/// <summary>
/// Get the factory for <see cref="IRepository{T}"/> where T is an entity type.
/// </summary>
/// <typeparam name="T">The root type of the repository, typically an entity type.</typeparam>
/// <returns>
/// A factory that creates the <see cref="IRepository{T}"/>, given an EF <see cref="DbContext"/>.
/// </returns>
/// <remarks>
/// Looks first for a custom factory in <see cref="_repositoryFactories"/>.
/// If not, falls back to the <see cref="DefaultEntityRepositoryFactory{T}"/>.
/// You can substitute an alternative factory for the default one by adding
/// a repository factory for type "T" to <see cref="_repositoryFactories"/>.
/// </remarks>
public Func<DbContext, object> GetRepositoryFactoryForEntityType<T>() where T : class
{
return GetRepositoryFactory<T>() ?? DefaultEntityRepositoryFactory<T>();
}
/// <summary>
/// Default factory for a <see cref="IRepository{T}"/> where T is an entity.
/// </summary>
/// <typeparam name="T">Type of the repository's root entity</typeparam>
protected virtual Func<DbContext, object> DefaultEntityRepositoryFactory<T>() where T : class
{
return dbContext => new EFRepository<T>(dbContext);
}
/// <summary>
/// Get the dictionary of repository factory functions.
/// </summary>
/// <remarks>
/// A dictionary key is a System.Type, typically a repository type.
/// A value is a repository factory function
/// that takes a <see cref="DbContext"/> argument and returns
/// a repository object. Caller must know how to cast it.
/// </remarks>
private readonly IDictionary<Type, Func<DbContext, object>> _repositoryFactories;
}
}
Here's the code that calls the factory:
using System;
using Data.Contracts;
using Data.Helpers;
using Models;
namespace Data
{
/// <summary>
/// The "Unit of Work"
/// 1) decouples the repos from the controllers
/// 2) decouples the DbContext and EF from the controllers
/// 3) manages the UoW
/// </summary>
/// <remarks>
/// This class implements the "Unit of Work" pattern in which
/// the "UoW" serves as a facade for querying and saving to the database.
/// Querying is delegated to "repositories".
/// Each repository serves as a container dedicated to a particular
/// root entity type such as a <see cref="Url"/>.
/// A repository typically exposes "Get" methods for querying and
/// will offer add, update, and delete methods if those features are supported.
/// The repositories rely on their parent UoW to provide the interface to the
/// data layer (which is the EF DbContext in this example).
/// </remarks>
public class UnitOfWork : IUnitOfWork, IDisposable
{
public UnitOfWork(IRepositoryProvider repositoryProvider)
{
CreateDbContext();
repositoryProvider.DbContext = DbContext;
RepositoryProvider = repositoryProvider;
}
// Repositories
public IRepository<Event> Events { get { return GetStandardRepo<Event>(); } }
public IRepository<Candidate> Candidates { get { return GetStandardRepo<Candidate>(); } }
/// <summary>
/// Save pending changes to the database
/// </summary>
public void Commit()
{
//System.Diagnostics.Debug.WriteLine("Committed");
DbContext.SaveChanges();
}
protected void CreateDbContext()
{
DbContext = new UnicornsContext();
// Do NOT enable proxied entities, else serialization fails
DbContext.Configuration.ProxyCreationEnabled = false;
// Load navigation properties explicitly (avoid serialization trouble)
DbContext.Configuration.LazyLoadingEnabled = false;
// Because Web API will perform validation, I don't need/want EF to do so
DbContext.Configuration.ValidateOnSaveEnabled = false;
}
protected IRepositoryProvider RepositoryProvider { get; set; }
private IRepository<T> GetStandardRepo<T>() where T : class
{
return RepositoryProvider.GetRepositoryForEntityType<T>();
}
private T GetRepo<T>() where T : class
{
return RepositoryProvider.GetRepository<T>();
}
private UnicornsContext DbContext { get; set; }
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (DbContext != null)
{
DbContext.Dispose();
}
}
}
#endregion
}
}
It seems to me that the factory makes things more complicated that they need be. Am I correct and should I do this a simpler way such as with something like:
private IRepository<xx> = new GenericRepository<xx>(dbContext);
One more point. In my application I am using Unity. So would it be even easier to just specify the needed repositories in the constructor and have Unity create the repositories for me. If I did this then is there a way I could pass around the dbContext so it could be used by Unity when creating the repository? Has anyone used Unity to create repositories like this?
OK. Here's my best shot:
The point of keeping repositories in a cache is to ensure that the repository is only initiated once per request. The repository cache is in the RepositoryProvider class and is exposed to the UnitOfWork by the GetRepositoryForEntityType method. So the advantage is that the unit of work is not concerned with caching or creation of repositories.
The RepositoryProvider class is instantiated once per unit of work. (NB - it is desirable to create the repositories new for every request). The RepositoryProvider keeps the repositories in a dictionary using the type as a key. This is fine when using the generic repository base which has a Type parameter. But what if you have created a custom repository? In this example the creation of repositories by type is handed off to the RepositoryFactories class via the MakeRepository method. The advantage is that creating repositories is separated from caching.
The RepositoryFactories class knows when to make a custom repository because it contains a dictionary that uses Type as a key and a function as a value. The function is the constructor for a custom repository. If there's a value in the dictionary then use that constructor otherwise just use the generic base constructor.
All this means that as you add entities you do not have to modify any of these classes unless you create a custom repository. And when you do that all you have to do is add an entry to the dictionary in RepositoryFactories
Looked for a method on the MvcContrib.TestHelper.RouteTestingExtensions class named ShouldNotMap. There is ShouldBeIgnored, but I don't want to test an IgnoreRoute invocation. I want to test that a specific incoming route should not be mapped to any resource.
Is there a way to do this using MvcContrib TestHelper?
Update
Just tried this, and it seems to work. Is this the correct way?
"~/do/not/map/this".Route().ShouldBeNull();
I think you are looking for the following:
"~/do/not/map/this".ShouldBeIgnored();
Behind the scenes this asserts that the route is processed by StopRoutingHandler.
I was looking for the same thing. I ended up adding the following extension methods to implement ShouldBeNull and the even shorter ShouldNotMap:
In RouteTestingExtensions.cs:
/// <summary>
/// Verifies that no corresponding route is defined.
/// </summary>
/// <param name="relativeUrl"></param>
public static void ShouldNotMap(this string relativeUrl)
{
RouteData routeData = relativeUrl.Route();
routeData.ShouldBeNull(string.Format("URL '{0}' shouldn't map.", relativeUrl));
}
/// <summary>
/// Verifies that the <see cref="RouteData">routeData</see> is null.
/// </summary>
public static void ShouldNotMap(this RouteData routeData)
{
routeData.ShouldBeNull("URL should not map.");
}
In GeneralTestExtensions.cs :
///<summary>
/// Asserts that the object should be null.
///</summary>
///<param name="actual"></param>
///<param name="message"></param>
///<exception cref="AssertFailedException"></exception>
public static void ShouldBeNull(this object actual, string message)
{
if (actual != null)
{
throw new AssertFailedException(message);
}
}