Scenario:
asp mvc application: WebSite. WCF service: Service, with DoSmth() method. I call Service from the WebSite.
What is the proper way to call Service.DoSmth()?
I can create it all time I need to use it, like this:
using (var service = new ServiceClient()) {
service.DoSmth();
}
Or I can add Service field to the controller class and create the Service in controller's constructor.
private Service service;
public MyController() {
service = new ServiceClient();
}
I want to know, whats the difference, regarding to sessions, because, if we create the Service in constructor, we create one long session. So what about session time-outs or something like this? And what are the benefits from the other points of views?
Another question is, where to call service.DoSmth()? I've read about mvc pattern, and I think, that the proper way due the pattern is to call it from models, because models should do the work, and controller is only a "manager", but I saw many examples, where people use models only like containers, to pass data from controller to view. So can somebody clarify it for me.
.
In many cases, you want to reuse the same WCF Client Proxy, as this connection method yields the best performance. Reusing the same proxy can be particularly beneficial if you use security features, which have a high initial security negotiation cost. Note: you surely need to check the state of the client proxy before using.
In the event that reusing the same client proxy is not an option, then consider using a ChannelFactory proxy that uses caching.
The following links provide good information and some guidance regarding best practices: http://blogs.msdn.com/b/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx
http://msdn.microsoft.com/en-us/library/aa738757.aspx
Related
I am currently developing an ASP.Net MVC web application that requires username and password authentication. I started looking into using ASP.Net Identity for this however I have a very important requirement, the requirement is that the web application itself has no direct access to any databases, all DB Access is to be exposed to the application via an internal REST service. This is due to certain security polices we follow.
I realise that ASP.Net identity is capable of supporting external authentication methods but my question is split into 2 parts.
1) How would I configure ASP.Net Identity to use my custom REST service for authentication?
2) How would I go about developing a service that can be used by Identity for authentication ? (what would need to be returned from the service to ASP.Net Identity)
Any help on this would be most appreciated.
I just did what you are asking about. First, as FPar suggested, you need to implement an IUserStore and pass that to your UserManager. Your custom IUserStore will implement the interface, I used Resharper to generate stubs, but instead of using entity framework, you will use HttpClient to make calls to your REST service.
The REST service will have one action on a controller, I called my identityController, for each of the interface methods you actually need. I implemented the userstore, userloginstore and the rolestore, with code for about 10 calls I actually used. The identitycontroller then is what actually accesses the database.
I also retained the fully async pattern, using async REST calls and Database looks, both with and without entity framework. A shortened version of my data access code is in another question here, regarding IUserLoginStore::AddLoginAsync. In that class I actually used the original entityframework implementation of the user store for part of work, and eventually settled on plain (except for async) ado.net for the parts I couldn't make work that way. The tables are simple enough, using your ORM of choice would not take a lot of time.
Good luck!
You want to implement your own IUserStore and then pass a reference to the UserManager. Look into the Startup and the IdentityConfig files in the standarad ASP.NET MVC with individual user account authentication, to see, how to use them.
You can look here for an IUserStore implementation with entity framework. This is a template, you could start from and change it to your needs. However, you don't have to implement all interfaces, just implement the interfaces, you really need. The UserManager is able to handle that (it throws an exception, if you call a method, that requires an interface, that you don't implement.)
These are two excellent articles on this subject:
http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
http://www.codeproject.com/Articles/762428/ASP-NET-MVC-and-Identity-Understanding-the-Basics
I'm wondering if it's possible to service up WCF services via MVC. I've seen a few posts about this as it relates to RESTful services, but I'm not looking to create a RESTful service.
I've also seen this topic covered as far as serving up .svc files from MVC, but I'm not looking for that either.
Basically, I'm just looking to expose my WCF services via MVC, instead of a typical Wep App type structure with svc files.
so instead of having ttp://localhost/MyService.svc, I would just have ttp://localhost/MyService and that would go to a controller that would return the data.
Is it possible to have a "servicehost" controller? I would assume that the biggest obstacle to this would be that IIS handles the service a certain way based on the .svc extension - would some kind of custom handler have to be set up for something like this?
Any thoughts?
You can do this without MVC (or, it seems, with it too)
http://geekswithblogs.net/michelotti/archive/2010/08/21/restful-wcf-services-with-no-svc-file-and-no-config.aspx
http://geekswithblogs.net/michelotti/archive/2010/09/22/wcf-rest-services-inside-mvc-projects.aspx
My ASP.NET MVC controller constructors create an instance of a service class by supplying it with (among other things) a ModelStateWrapper (similar to this article). Since this object is handled through a reference, any changes made to it in the service are reflected when the controller accesses that ModelStateWrapper object.
I need to convert that logical service layer into WCF services that will be hosted in IIS.
Assuming I want to continue performing validation in the service layer, which approach is better?
Pass the ModelStateWrapper object by reference (possible according to MSDN) with each service operation
Keep track of errors in the service and have the client explicitly retrieve a list of errors after any/all service operations are performed
Any other suggestions or links to articles that would help me perform validation behind a WCF service?
It should be noted that these services will eventually be consumed by a variety of UIs (ASP.NET MVC, Winform, Console, maybe even third-party).
Since you already have everything in place and working, pass the ModelStateWrapper over the wire to WCF service. Let it fill it out and send back.
The other platforms can use this same wrapper to get the error information.
There are two classes in my project (using ASP.NET MVC): AuthenticationService, and ProfileService.
When a new user registers at my site the Authentication controller's Register action calls a Register method in IAuthenticationService, which creates an authentication record for the user according to whichever concrete authentication module the interface is referring to (injected into the controller's constructor).
As part of the registration process a profile record is created for the user, which is created by calling CreateProfile(User) on the injected IProfileService.
At the moment the controller is calling both services, but I like the idea of my controller performing as little business logic as possible. I'm wondering if I have any other options besides letting the authentication service know about the profile service, which in turn would require any future implementation of IAuthenticationService to know to call CreateProfile? I can't help feel that has code smell written all over it.
Another possibility is to have a third service, {I,}RegistrationService, be responsible for the logic.
What's the recommended, or preferred way of handling this situation? Thanks
I like the third approach. I have a similar situation in my app where the controller needs multiple domain level services to perform a task, and the code gets a bit verbose for a controller. In particular, i have an event management system which allows for photo uploads. In addition to repositories and IAuthService, physical storage is handled by an IFileSystem (we can switch between local and S3), image manipulation by IThumbnailer, sweeping/cleanup handled by a IBackgroundTask.
What i've begun doing is create application services in addition to domain services to handle the responsibility, so that the container is now only injected primarily with app services (option 3 in your case)
I would go with an {I}RegistrationService which depends on the IAuthenticationService and IProfile services.
As a rule I aim to have a single Service Dependency per Controller
If the controller is tasked with registering users and creating profiles, whats the matter? It's OK for a controller to call multiple services. The controller serves a purpose and it doesn't have to be insanely granular.
Creating a third controller for general registration that uses an interface reference to authentication and profile would likely be the better route though. Then authentication and profiles aren't coupled.
I'm using ASP.NET MVC and I am trying to separate a lot of my logic. Eventually, this application will be pretty big. It's basically a SaaS app that I need to allow for different kinds of clients to access. I have a two part question; the first deals with my general design and the second deals with how to utilize in ASP.NET MVC
Primarily, there will initially be an ASP.NET MVC "client" front-end and there will be a set of web-services for third parties to interact with (perhaps mobile, etc).
I realize I could have the ASP.NET MVC app interact just through the Web Service but I think that is unnecessary overhead.
So, I am creating an API that will essentially be a DLL that the Web App and the Web Services will utilize. The API consists of the main set of business logic and Data Transfer Objects, etc. (So, this includes methods like CreateCustomer, EditProduct, etc for example)
Also, my permissions requirements are a little complicated. I can't really use a straight Roles system as I need to have some fine-grained permissions (but all permissions are positive rights). So, I don't think I can really use the ASP.NET Roles/Membership system or if I can it seems like I'd be doing more work than rolling my own. I've used Membership before and for this one I think I'd rather roll my own.
Both the Web App and Web Services will need to keep security as a concern. So, my design is kind of like this:
Each method in the API will need to verify the security of the caller
In the Web App, each "page" ("action" in MVC speak) will also check the user's permissions (So, don't present the user with the "Add Customer" button if the user does not have that right but also whenever the API receives AddCustomer(), check the security too)
I think the Web Service really needs the checking in the DLL because it may not always be used in some kind of pre-authenticated context (like using Session/Cookies in a Web App); also having the security checks in the API means I don't really HAVE TO check it in other places if I'm on a mobile (say iPhone) and don't want to do all kinds of checking on the client
However, in the Web App I think there will be some duplication of work since the Web App checks the user's security before presenting the user with options, which is ok, but I was thinking of a way to avoid this duplication by allowing the Web App to tell the API not check the security; while the Web Service would always want security to be verified
Is this a good method? If not, what's better? If so, what's a good way of implementing this. I was thinking of doing this:
In the API, I would have two functions for each action:
// Here, "Credential" objects are just something I made up
public void AddCustomer(string customerName, Credential credential
, bool checkSecurity)
{
if(checkSecurity)
{
if(Has_Rights_To_Add_Customer(credential)) // made up for clarity
{
AddCustomer(customerName);
}
else
// throw an exception or somehow present an error
}
else
AddCustomer(customerName);
}
public void AddCustomer(string customerName)
{
// actual logic to add the customer into the DB or whatever
// Would it be good for this method to verify that the caller is the Web App
// through some method?
}
So, is this a good design or should I do something differently?
My next question is that clearly it doesn't seem like I can really use [Authorize ...] for determining if a user has the permissions to do something. In fact, one action might depend on a variety of permissions and the View might hide or show certain options depending on the permission.
What's the best way to do this? Should I have some kind of PermissionSet object that the user carries around throughout the Web App in Session or whatever and the MVC Action method would check if that user can use that Action and then the View will have some ViewData or whatever where it checks the various permissions to do Hide/Show?
What you propose will not work. Actions can be cached, and when they are, the action (and hence your home-rolled security) does not run. ASP.NET membership, however, still works, since the MVC caching is aware of it.
You need to work with ASP.NET membership instead of trying to reinvent it. You can, among other things:
Implement a custom membership provider or role provider.
Subtype AuthorizeAttribute and reimplement AuthorizeCore.
Use Microsoft Geneva/Windows Identity Foundation for claims-based access.
Also, I completely disagree with ChaosPandion, who suggests making structural changes in your code before profiling. Avoiding exceptions for "performance" reasons is absurd -- especially the idea that the mere potential to throw an exception for invalid users will somehow tank the performance for valid users. The slowest part of your code is likely elsewhere. Use a profiler to find the real performance issues instead of jumping on the latest micro-"optimization" fad.
The correct reason to avoid exceptions for authorizations is that the correct way to indicate an attempt at unauthorized access in a web app is to change the HTTP status code to 401 Unauthorized, not throwing an exception (which would return 500).
Define your authorisation requirements as a domain service so they are available to both the web and web service implementations.
Use an authorisation filter to perform your authorisation checks within the web application, this should be as simple as creating an auth request object and then passing it to your auth domain service.
If the authorisation fails, return the correct error - a 401 as indicated by Craig Stuntz.
ALWAYS authorise the action. If you can hide the link to unauthorised users - thats nice.
Simplify your views / view logic by writing a HtmlHelper extension method that can show / hide things based on a call to the auth domain service.
To use your authorisation service from the web service is simply a matter of constructing the auth request object from something passed in via the service message instead of from a cookie passed by the users browser.