Create a custom Http method - asp.net-core

Is it possible to create our own HTTP method by just overriding the HttpMethodAttribute class and specify our own supportedMethods ?
In fact, depending on the case, we need to return the View as complete view with the _Layout, and sometimes we just need to return the PartialView of this view. So my idea is to put an custom attribute, like [HttpPartial] and so the client will tell, depending on the methods used in the request, if it wants the complete view (GET method) or the partial view (PARTIAL method).

Yes, that's possible for APIs. You can look at how the HttpGetAttribute is implemented, and roll your own for a custom method, replacing "get" with "foo":
/// <summary>
/// Identifies an action that supports the HTTP FOO method.
/// </summary>
public class HttpFooAttribute : HttpMethodAttribute
{
private static readonly IEnumerable<string> _supportedMethods = new[] { "FOO" };
/// <summary>
/// Creates a new <see cref="HttpFooAttribute"/>.
/// </summary>
public HttpFooAttribute()
: base(_supportedMethods)
{
}
/// <summary>
/// Creates a new <see cref="HttpFooAttribute"/> with the given route template.
/// </summary>
/// <param name="template">The route template. May not be null.</param>
public HttpFooAttribute(string template)
: base(_supportedMethods, template)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
}
}
Then apply it to your API action methods:
[Route("Bar")]
public class BarApiController : Controller
{
[HttpFoo("/"]
public IActionResult Foo()
{
return Ok("Foo");
}
}
Now you can request FOO https://your-api:44312/bar/.
This is less useful for actions returning views, as any HTML-rendering user agent only lets the user initiate GET or POST requests through hyperlinks and forms.
You could send more methods through an XMLHttpRequest or fetch(), but it'll require more documentation and client customization.
Don't break or hamper the web, don't invent new HTTP methods for your application logic. Simply use a query string parameter or send it in your body: &renderAsPartial=true, { "renderAsPartial": true }.
See the IANA's Hypertext Transfer Protocol (HTTP) Method Registry for existing methods and see RCF 7231 section 8.1 for how to register new HTTP methods.

Related

Using ASP.NET Core Identity for authenticating Controller usage

I have been developing a asp.net core razor application and I have stuck to using views and models. However, I added a frontend framework so making HTTP request is used quite often so I thought I would test out the Web API in asp.net core by adding a controller and it is awesome how easy it is to pass usable json arrays to the frontend. My issue is I implemented the following code to my razor application's startup.cs to restrict any non logged in users from accessing any other pages or page models unless logged in:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(cookieOptions => {
cookieOptions.Cookie.Name = "UserLoginCookie";
cookieOptions.LoginPath = "/Login/";
cookieOptions.ExpireTimeSpan = TimeSpan.FromMinutes(30);
cookieOptions.SlidingExpiration = true;
});
This works great except the issue I am finding is my test HomeController is still accessible (url/home/index) even if I am not logged in. Is there a way to use the identity authentication I used for my razor pages to restrict access to the controller for only logged in users. Also, for an extra layer of security I wanted to store a variable server side for the logged in user's ID and integrated that into the controller so i can limit my queries to that user without letting it be a HTTP parameter which could then allow anyone to access other users data.
Adding [Authorize] above the homecontroller class did the trick but not sure why I was required to use this tag to make it work.
If you add [Authorize] on the whole controller it will prevent all the methods in that class to be accessible. Requires the specified authorization
In this case the CookieAuthenticationDefaults.
If you have more than one you can specify the name of the policy you want it to check for
[Authorize(Roles = "Administrator")]
Here is the AuthorizeAttribute class for more information
using System;
namespace Microsoft.AspNetCore.Authorization
{
/// <summary>
/// Specifies that the class or method that this attribute is applied to requires the
specified authorization.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple =true,
Inherited = true)]
public class AuthorizeAttribute : Attribute, IAuthorizeData
{
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizeAttribute"/> class with
the specified policy.
/// </summary>
/// <param name="policy">The name of the policy to require for authorization.</param>
public AuthorizeAttribute(string policy)
{
Policy = policy;
}
/// <summary>
/// Gets or sets the policy name that determines access to the resource.
/// </summary>
public string? Policy { get; set; }
/// <summary>
/// Gets or sets a comma delimited list of roles that are allowed to access the resource.
/// </summary>
public string? Roles { get; set; }
/// <summary>
/// Gets or sets a comma delimited list of schemes from which user information is constructed.
/// </summary>
public string? AuthenticationSchemes { get; set; }
}
}

Why Swagger is not picking up the summary of an ApplicationService method in ABP Framework?

I have the following application service method.
public class MyAppService : AsyncCrudAppService<Entity, Dto, Guid, GetAllRequest, CreateRequest, UpdateRequest, GetRequest, DeleteRequest>, IMyAppService
{
/// <summary>
/// Return cities associated with zip code
/// </summary>
/// <param name="zipCode">Zip code to search. If null all cities are returned.</param>
/// <returns>Cities associated with zip code.</returns>
/// <exception cref="EntityNotFoundException">If zip code is provided but no associated city is found</exception>
/// <response code="404">If no city with zip code found</response>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<GetCitiesByZipCodeResponse> GetCitiesByZipCode(int? zipCode = null)
{
...
}
}
Even though I have a summary describing what the endpoint does, it is not displayed in swagger. What is the right way to add rich information to Swagger about app service methods?
It did pick up the effect of ProducesResponseType(StatusCodes.Status404NotFound) and showing 404 as possible response though.
Swagger for GetCitiesByZipCode
AppServices are automatically converted to Controllers. But your custom Swagger attributes are stripped off. If you have a such requirement, then create a new MyContoller and call your AppService methods inside the Controller. And disable remote service function for your Appservice with the following attribute
[RemoteService(IsEnabled = false)]
https://docs.abp.io/en/abp/latest/API/Auto-API-Controllers#remoteservice-attribute

User customizable validation with metadata saved in a database

I'm working on an application which should validate the model based on some metadata saved in a database. The purpose of this is to allow administrators change how some models are validated, without changing the code, depending on clients' preferences. The changes are applied for the entire application, not for specific users accessing it. How it is changed, doesn't matter at the moment. They could be modified directly on the database, or using an application. The idea is that they should be customizable.
Let's say i have the model "Person" with the property "Name" of type "string".
public class Person
{
public string Name { get; set; }
}
This model is used by my app which is distributed and istalled on several servers. Each of them is independent. Some users may want the Name to have maximum 30 letters and to be required when creating a new "Person", others may want it to have 25 and not to be required. Normally, this would be solved using data annotations, but those are evaluated during the compile time and are somehow "hardcoded".
Shortly, I want to find a way to customize and store in a database how the model validates, without the need of altering the application code.
Also, it would be nice to work with jquery validation and have as few request to database(/service) as possible. Besides that, i can't use any known ORM like EF.
You could create a custom validation attribute that validates by examining the metadata stored in the database. Custom validation attributes are easy to create, simply extend System.ComponentModel.DataAnnotations.ValidationAttribute and override the IsValid() method.
To get the client side rules that work with jQuery validation you will need to create a custom adapter for the type of your custom validation attribute that extends System.Web.Mvc.DataAnnotationsModelValidator<YourCustomValidationAttribute>. This class then needs to be registered in the OnApplicationStart() method of your Global.asax.
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(YourCustomValidationAttribute), typeof(YourCustomAdapter));
Here's an example adapter:
public class FooAdapter : DataAnnotationsModelValidator<FooAttribute>
{
/// <summary>
/// This constructor is used by the MVC framework to retrieve the client validation rules for the attribute
/// type associated with this adapter.
/// </summary>
/// <param name="metadata">Information about the type being validated.</param>
/// <param name="context">The ControllerContext for the controller handling the request.</param>
/// <param name="attribute">The attribute associated with this adapter.</param>
public FooAdapter(ModelMetadata metadata, ControllerContext context, FooAttribute attribute)
: base(metadata, context, attribute)
{
_metadata = metadata;
}
/// <summary>
/// Overrides the definition in System.Web.Mvc.ModelValidator to provide the client validation rules specific
/// to this type.
/// </summary>
/// <returns>The set of rules that will be used for client side validation.</returns>
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationRequiredRule(
String.Format("The {0} field is invalid.", _metadata.DisplayName ?? _metadata.PropertyName)) };
}
/// <summary>
/// The metadata associated with the property tagged by the validation attribute.
/// </summary>
private ModelMetadata _metadata;
}
This may also be useful if you would like to asynchronously call server side validation http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.108).aspx

NServiceBus, NHibernate and Multitenancy

We're using NServiceBus to perform document processing for a number of tenants.
Each tenant has their own database and we're using NHibernate for data access. In the web application we're using our IoC tool (StructureMap) to handle session management. Essentially we maintain a session factory for each tenant. We're able to identify the tenant from HttpContext.
When we kick off document processing using NServiceBus we have access to the tenant identifier. We need this tenant id to be available throughout the processing of the document (we have 2 sagas and fire off a number of events).
We would need to create a NHibernate SessionFactory for each tenant so would need some way of obtaining the tenant id when we configure StructureMap.
I've seen a few posts suggesting to use a message header to store the tenant identifier but am unsure how to:
Set a message header when we first submit a document (sending a SubmitDocumentCommand)
Reference the header when we configure StructureMap
Access the header within our sagas/handlers
Ensure the header flows from one message to the next. When we send a SubmitDocumentCommand it is handled by the DocumentSubmissionSaga. If the submission succeeds we will send off a DocumentSubmittedEvent. We'd want to make sure the tenant id is available at all points in the process.
I believe with this information I can successfully implement multitenancy with NHibernate but anything more specific to this scenario would be appreciated.
You can flow the header using a message mutator that registers itself: Here is a quick example from my own code. And you can always use Bus.CurrentMessageContext.Headers to set/get to the header anywhere...
Hope this helps :)
/// <summary>
/// Mutator to set the channel header
/// </summary>
public class FlowChannelMutator : IMutateOutgoingTransportMessages, INeedInitialization
{
/// <summary>
/// The bus is needed to get access to the current message context
/// </summary>
public IBus Bus { get; set; }
/// <summary>
/// Keeps track of the channel
/// </summary>
/// <param name="messages"></param>
/// <param name="transportMessage"></param>
public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
{
if (Bus.CurrentMessageContext != null &&
Bus.CurrentMessageContext.Headers.ContainsKey("x-messagehandler-channel"))
{
if (!transportMessage.Headers.ContainsKey("x-messagehandler-channel"))
{
transportMessage.Headers["x-messagehandler-channel"] =
Bus.CurrentMessageContext.Headers["x-messagehandler-channel"];
}
}
}
/// <summary>
/// Initializes
/// </summary>
public void Init()
{
Configure.Instance.Configurer.ConfigureComponent<FlowChannelMutator>(DependencyLifecycle.InstancePerCall);
}
}

Web Service nHibernate SessionFactory issue

I have a C# .Net Web Service. I am calling a dll (C# .Net) that uses nHibernate to connect to my database. When I call the dll, it executes a query to the db and loads the parent Object "Task". However, when the dll tries to access the child objects "Task.SubTasks", it throws the following error:
NHibernate.HibernateException failed to lazily initialize a collection of role: SubTasks no session or session was closed
I'm new to nHibernate so not sure what piece of code I'm missing.
Do I need to start a Factory session in my web service before calling the dll? If so, how do I do that?
EDIT: Added the web service code and the CreateContainer() method code. This code gets called just prior to calling the dll
[WebMethod]
public byte[] GetTaskSubtask (string subtaskId)
{
var container = CreateContainer(windsorPath);
IoC.Initialize(container);
//DLL CALL
byte[] theDoc = CommonExport.GetSubtaskDocument(subtaskId);
return theDoc;
}
/// <summary>
/// Register the IoC container.
/// </summary>
/// <param name="aWindsorConfig">The path to the windsor configuration
/// file.</param>
/// <returns>An initialized container.</returns>
protected override IWindsorContainer CreateContainer(
string aWindsorConfig)
{
//This method is a workaround. This method should not be overridden.
//This method is overridden because the CreateContainer(string) method
//in UnitOfWorkApplication instantiates a RhinoContainer instance that
//has a dependency on Binsor. At the time of writing this the Mammoth
//application did not have the libraries needed to resolve the Binsor
//dependency.
IWindsorContainer container = new RhinoContainer();
container.Register(
Component.For<IUnitOfWorkFactory>().ImplementedBy
<NHibernateUnitOfWorkFactory>());
return container;
}
EDIT: Adding DLL code and repository code...
DLL Code
public static byte[] GetSubtaskDocument(string subtaskId)
{
BOESubtask task = taskRepo.FindBOESubtaskById(Guid.Parse(subtaskId));
foreach(subtask st in task.Subtasks) <--this is the line that throws the error
{
//do some work
}
}
Repository for task
/// <summary>
/// Queries the database for the Subtasks whose ID matches the
/// passed in ID.
/// </summary>
/// <param name="aTaskId">The ID to find matching Subtasks
/// for.</param>
/// <returns>The Subtasks whose ID matches the passed in
/// ID (or null).</returns>
public Task FindTaskById(Guid aTaskId)
{
var task = new Task();
using (UnitOfWork.Start())
{
task = FindOne(DetachedCriteria.For<Task>()
.Add(Restrictions.Eq("Id", aTaskId)));
UnitOfWork.Current.Flush();
}
return task;
}
Repository for subtask
/// <summary>
/// Queries the database for the Subtasks whose ID matches the
/// passed in ID.
/// </summary>
/// <param name="aBOESubtaskId">The ID to find matching Subtasks
/// for.</param>
/// <returns>The Subtasks whose ID matches the passed in
/// ID (or null).</returns>
public Subtask FindBOESubtaskById(Guid aSubtaskId)
{
var subtask = new Subtask();
using (UnitOfWork.Start())
{
subtask = FindOne(DetachedCriteria.For<Subtask>()
.Add(Restrictions.Eq("Id", aSubtaskId)));
UnitOfWork.Current.Flush();
}
return subtask;
}
You have apparently mapped a collection in one of your NHibernate data classes with lazy loading enabled (or better: not disabled, as it is the default behavior). NHibernate loads the entity and creates a proxy for the mapped collections. As soon as they are accessed, NHibernate attempts to load the items for that collection. But if you close your NHibernate session before that happens, the error you received will occur. You are probably exposing your data object through your web service to the web service client. During the serialization process, the XmlSerializer tries to serialize the collection which prompts NHibernate to populate it. As the session is closed, the error occurs.
Two ways to prevent this:
close the session after the response has been sent
or
disable lazy loading for your collections so that they are loaded instantly
Addition after the above edits:
in your repository, you start UnitsOfWork within a using-statement. They are being disposed as soon as the code is completed. I don't know the implementation of UnitOfWork but i assume it controls the lifetime of the NHibernate session. By disposing the UnitOfWork, your are probalby closing the NHibernate session. As your mapping initializes collections lazy loaded, these collections are not yet populated and the error occurs. NHibernate needs the exact instance of the session that loaded an entity to populate lazily initialized collections.
You will run into problems like this if you use lazy loading and have a repository that closes the session before the response is complete. One option would be to initialize the UnitOfWork at the start of the request and close it after the response is complete (for instance in Application_BeginRequest, Application_EndRequest in Global.asax.cs). That would of course mean a close integration of your repository into the web service.
In any case, creating a Session for a single request in combination with lazy loading is a bad idea and is very likely to create similar problems in the future. If you can't change the repository implementation you might probably have to disable lazy loading.
Using Garland's feedback I resolved the issue. I removed the UnitOfWork(s) code from the repository in the DLL and wrapped the Web Service call to the DLL in a UnitOfWork See code mods below:
Web Service
[WebMethod]
public byte[] GetSubtaskDocument (string subtaskId)
{
var container = CreateContainer(windsorString);
IoC.Initialize(container);
byte[] theDoc;
using (UnitOfWork.Start())
{
//DLL call
theDoc = CommonExport.GetSubtaskDocument(subtaskId);
UnitOfWork.Current.Flush();
}
return theDoc;
}
Repository call in the DLL
public Subtask FindSubtaskById(Guid aSubtaskId)
{
return FindOne(DetachedCriteria.For<Subtask>()
.Add(Restrictions.Eq("Id", aSubtaskId)));
}