I have an existing ASP.NET application and I want it to act as an SAML2 SP using SustainSys SAML2. The documentation says that I should use the web.config file but it gets ignored on .NET Core.
So, how do I start?
I assume I should write a bit of code to my Startup class, but what and where? The thread linked above tells some things but I need more details. How do I set Saml2 as the default challenge protocol for authentication?
I added the code from the documentation (services.AddAuthentication().AddSaml2(...); in void ConfigureServices() and even app.UseAuthorization(); in void Configure()) and when I try to add the [Authorize] attribute to a controller, I get an exception telling me "a middleware was not found that supports authorization. Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code."
Use the Sustainsys.Saml2.AspNetCore2 package and add it in startup.
Web.config is not used on AspNet Core, you have to configure in startup.
I need to delete a specific cookie when my app starts, before heading to home page.
I had this inside a controller action method, with a redirect to home page, setting up my startup class to use as route template this controller and action method.
However, there must be a way I can set up a method to delete this cookie, and execute it from startup?
In ASP.NET, this would be done in the methods of global.asax (often in Session_Start(...)). Read more here and here.
In ASP.NET Core, the startup.cs class is where all configurations of services are defined, as well as pipeline requests are managed.
You need to make your own custom middleware for this. Middleware is software that's assembled into an app pipeline to handle requests and responses.
There is another SO question on this topic here (with an answer):
ASP .NET Core webapi set cookie in middleware
For more in-depth cookie management look at this article:
https://www.seeleycoder.com/blog/cookie-management-asp-net-core/
More on middleware:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-2.2
I'm a newer developer who has been developing a RESTful API with Web API 2 within an instance of Umbraco 6. After some research on http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api, I added the attribute to my controller as such:
[EnableCors(origins: "http://example.com,http://example.local", headers: "*", methods: "*")] //CORS TESTING
public class PropertiesController : UmbracoApiController
{
//Code Hidden
}
I'm finding that I can go to a site like http://codebeautify.org/jsonvalidate and pull in my JSON through the endpoint URL and validate it even though I didn't allow that host to call my API.
Following the instructions from the asp.net link above, I noticed that my solution doesn't have an "App_Start" folder with a WebApiConfig.CS file, so I was never able to add the config.EnableCors(); code which I think may be the underlying issue? I'm not sure how to continue at this point because to get this far, I just had to add a new Web API Controller Class to '/App_Code' and then inherit UmbracoApiController.
You can create the WebApiConfig.cs if you wish and call it from Global.asax.cs . Or just call EnableCors() wherever you have the config. This is a simple answer with an example https://stackoverflow.com/a/29397652/3520146 .
I used to place my controllers into a separate Class Library project in Mvc Web Api. I used to add the following line in my web api project's global.asax to look for controllers in the separate project:
ControllerBuilder.Current.DefaultNamespaces.Add("MyClassLibraryProject.Controllers");
I never had to do any other configuration, except for adding the above line. This has always worked fine for me.
However I am unable to use the above method to do the same in WebApi2. It just doesn't work. The WebApi2 project still tries to find the controllers in its own project's controllers folder.
-- Giving little summary update after 2 months (As I started bounty on this):
I have created a WebApiOne solution, it has 2 projects, the first one is WebApi project, and the second is a class library for controllers. If I add the reference to the controllers class library project into the WebApi project, all works as expected. i.e. if i go to http://mydevdomain.com/api/values i can see the correct output.
I have now create a second project called WebApiTwo, it has 2 projects, the first one is WebApi2 project, and the second is a class library for controllers. If I add the reference to the controllers class library project to the WebApi2 project, it doest NOT work as expected. i.e. if i go to http://mydevdomain.com/api/values i get "No type was found that matches the controller named 'values'."
for the first project i am not doing any custom settings at all, i do NOT have:
ControllerBuilder.Current.DefaultNamespaces.Add("MyClassLibraryProject.Controllers");
in my global.asax, and i have not implemented any custom solutions proposed by StrathWeb in two of his blog posts, as i think its not applicable any more; because all works just by adding the reference of the controller project to the WebApi project.
So i would expect all to work same for WebApi2 ... but its not. Has anyone really tried doing this in WebAPi2 ?
I have just confirmed that this works fine. Things to check:
References: Does your main Web API project reference the external class library?
Routing: Have you set up any routes that might interfere with the external controllers?
Protection Level: Are the controllers in the external library public?
Inheritance: Do the controllers in the external library inherit from ApiController?
Versioning: Are both your Web API project and class library using the same version of the Web API libraries?
If it helps, I can package up my test solution and make it available to you.
Also, as a point to note, you don't need to tell Web API to find the controllers with the line you added to Global.asax, the system finds the controllers automatically provided you have them referenced.
It should work as is. Checklist
Inherit ApiController
End controller name with Controller. E.g. ValuesController
Make sure WebApi project and class library project reference same WebApi assemblies
Try to force routes using attribute routing
Clean the solution, manually remove bin folders and rebuild
Delete Temporary ASP.NET Files folders. WebApi and MVC cache controller lookup result
Call `config.MapHttpAttributeRoutes(); to ensure framework takes attribute routes into consideration
Make sure that the method you are calling is made to handle correct HTTP Verb (if it is a GET web method, you can call via browser URL, if it is POST you have to otherwise craft a web request)
This controller:
[RoutePrefix("MyValues")]
public class AbcController : ApiController
{
[HttpGet]
[Route("Get")]
public string Get()
{
return "Ok!";
}
}
matches this url:
http://localhost/MyValues/Get (note there is no /api/ in route because it wasn't specified in RoutePrefix.
Controller lookup caching:
This is default controller resolver. You will see in the source code that it caches lookup result.
/// <summary>
/// Returns a list of controllers available for the application.
/// </summary>
/// <returns>An <see cref="ICollection{Type}" /> of controllers.</returns>
public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)
{
HttpControllerTypeCacheSerializer serializer = new HttpControllerTypeCacheSerializer();
// First, try reading from the cache on disk
List<Type> matchingTypes = ReadTypesFromCache(TypeCacheName, IsControllerTypePredicate, serializer);
if (matchingTypes != null)
{
return matchingTypes;
}
...
}
Was running into same scenario and #justmara set me on the right path. Here's how to accomplish the force loading of the dependent assemblies from #justmara's answer:
1) Override the DefaultAssembliesResolver class
public class MyNewAssembliesResolver : DefaultAssembliesResolver
{
public override ICollection<Assembly> GetAssemblies()
{
ICollection<Assembly> baseAssemblies = base.GetAssemblies();
List<Assembly> assemblies = new List<Assembly>(baseAssemblies);
var controllersAssembly = Assembly.LoadFrom(#"Path_to_Controller_DLL");
baseAssemblies.Add(controllersAssembly);
return baseAssemblies;
}
}
2) In the configuration section, replace the default with the new implementation
config.Services.Replace(typeof(IAssembliesResolver), new MyNewAssembliesResolver());
I cobbled this syntax together using pointers from this blog:
http://www.strathweb.com/2013/08/customizing-controller-discovery-in-asp-net-web-api/
As others have said, you know if you are running into this issue if you force the controller to load by directly referencing it. Another way is to example the results of CurrentDomain.GetAssemblies() and see if your assembly is in the list.
Also: If you are self-hosting using OWIN components you WILL run into this. When testing keep in mind that the DefaultAssembliesResolver will NOT kick in until the first WebAPI request is submitted (it took me awhile to realize that).
Are you sure that your referenced assembly was loaded BEFORE IAssembliesResolver service called?
Try to insert some dummy code in your application, something like
var a = new MyClassLibraryProject.Controllers.MyClass();
in configuration method (but don`t forget, that compiler can "optimize" this code and totally remove it, if "a" is never used).
I've had similar issue with assembly loading order. Ended up with force loading dependent assemblies on startup.
You need to tell webapi/mvc to load your referrenced assembly. You do that with the compilation/assemblies section in your web.config.
<compilation debug="true" targetFramework="4.5.2">
<assemblies>
<add assembly="XYZ.SomeAssembly" />
</assemblies>
</compilation>
Simple as that. You can do it with code the way #user1821052 suggested, but this web.config version will have the same effect.
Apart from what has been said already:
Make sure you don't have two controllers of the same name in different namespaces.
Just had the case where one controller (foo.UserApiController) should be partially migrated to a new namespace (bar.UserApiController) and URI. The old controller was mapped by convention to /userapi, the new one was attribute-routed via RoutePrefix["api/users"]. The new controller didn't work until I renamed it to bar.UserFooApiController.
When using AttributeRouting it is easily forgettable to decorate your methods with the Route Attribute, especially when you are using the RoutePrefix Attribute on your controller class. It seems like your controller assembly wasn't picked up by the web api pipeline then.
If your class library is built with EF then make sure you have the connection string specified in the App.config for the class library project, AND in the Web.config for your Web API MVC project.
I'm developing a ASP.NET MVC 2 web application. So far, I managed to define access rules for every controller function, using "RequiresRole" attribute.
Suddenly, this way of defining access rules stopped working (now every user can invoke any of the controller methods). :S. I tried debugging, and it seems that user-roles are correct. I tried reviewing web.config, but did not find anything suspicious.
Don't know what else could be the problem.
Any ideas??
RequresRoleAttribute is intended for use on WCF domain data services, not MVC controllers. I believe the attribute you should use is AuthorizeAttribute, setting the Roles parameter.