asp.net web api generate url for a resource - asp.net-web-api

i am trying to generate a url for a resource using asp.net web api.
I can do that pretty easily in side ApiController, but what about I am not in the ApiController context?

The long way is to get the request, dig out the Configuration and the RouteData from the properties collection, create yourself a ControllerContext and then you can use UrlHelper to general Urls.
There may be an easier way, but I haven't found it yet.

Related

Autofac OWIN Web API current scope

In a OWIN Web API method you can get the current scope within a Web API method like so...
public IHttpActionResult GetTaxRate()
{
var scope = Request.GetOwinContext().GetAutofacLifetimeScope();
ISomething mySomething = scope.Resolve<ISomething>();
Is there anyway to get the current scope through a static method instead of a member on the ApiController?
In short: Nope.
Autofac puts its request scope in the OWIN context so it can be shared across middleware components, so the question of how to access the Autofac-specific scope from an OWIN context is more a question of "How do you get the OWIN context?" OWIN doesn't have a static mechanism like HttpContext, so you're stuck there. That's not an Autofac issue, that's the design of OWIN.
Web API in particular also doesn't have a static notion of something like HttpContext. That's a Web API restriction, not an Autofac restriction. The request scope (and other request context things) in Web API flows with the request message. There's some Autofac-specific doc on this here but, again, this isn't an Autofac-specific issue - it's the design of Web API.

Autofac with Web API: inject dependencies from HttpRequestMessage?

I have a need to inject certain values from the HttpRequestMessage (mostly revolving around identity) into some of my objects.
As I understand it, using HttpSession.Current is not recommended in the Web Api framework. How do I access the HttpRequestMessage for user's Identity and other attributes such as user's IP address, UserAgent, etc. during binding of my dependencies in Autofac?
You can use builder.RegisterHttpRequestMessage() while you're building your dependency container. After that, anything that takes an HttpRequestMessage as a dependency will get the current message.
Adding to the accepted answer of #Travis Illig, the full call should be something like this:
builder.RegisterHttpRequestMessage(System.Web.Http.GlobalConfiguration.Configuration);

How can I get access to the HttpRequestMessage in Ninject?

I currently have filters and message handlers that add values to the request properties (i.e. via HttpRequestMessage.Properties.Add). I'd like to use these values in constructor injection of my controllers using Ninject. How can I access the current request object using Ninject?
In ASP.NET MVC, I was able to use HttpContext.Current in a Kernel.Bind<>().ToMethod() anonymous function. Web API doesn't have a static state object and I'd like to avoid creating one.

VS2013 (RTW): Authentication differences in SPA template vs MVC5 template?

I've been playing with the new ASP.NET identity offerings in the VS2013 RTW MVC template (for "indivual user accounts"), and it works great: I am able to integrate Facebook login while customizing the way the data is serialized.
All well and good, but I noticed that if I create a new SPA app (instead of MVC), the authentication story seems very different. As an example:
From the SPA template:
public AccountController()
: this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
{
}
public AccountController(UserManager<IdentityUser> userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
From the MVC template:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
This is just the difference in constructors of the Account controller. There are many, many other differences as well. With the MVC version I was able to easily derive my own context class from ApplicationDBContext, and use that to store my own tables alongside the authentication tables. I couldn't figure out how to customize the data storage in the SPA template.
Also, the SPA template includes and uses this class:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
The MVC template doesn't define (or use) this class.
I don't understand why there needs to be any differences at all between an MVC template and an SPA template.
Could anyone give me some guidance as to why authentication is handled so differently in these two templates? Starting a project from scratch, is there a preferred path to follow between the two? (It seems like the code in the MVC template is best, especially in terms of customizing how the data is stored by defining a custom EF Context class.)
Thanks...
-Ben
Take MVC and SPA project templates as Controller vs ApiController implementation sample.
As well as CookieAuthentication and oAuthAuthentication.
MVC uses Controller at the first request as well as all subsequent requests (having request defined Action Methods).
SPA uses Controller at the first request to SPA and all other interactions are handled by ApiController.
MVC uses cookie authentication.
SPA uses oAuth authentication.
Now in real apps, we need to take mix of both. Stating this, you can use the IdentityModel.cs (ApplicationDBContext) and it's customized copy of MVC project in your SPA too.
In oAuth implementation, the token is issued in GrantResourceOwnerCredentials method of ApplicationOAuthProvider. The user verification uses the same database of Identity framework by default. Moreover, oAuth provide authentication check in ApiController. In the sample implementation, oAuth's ResourceOwner flow is provided where user's username and password are verified.
In my opinion, templates are starting point examples.
I did notice the same thing when I first looked at all the posts about changing the model for the user and I couldn't find the model in the SPA template. Of course, the difference as #jd4u pointed out is that one is based on Controller and the other on ApiController.
So, I decided to see what it would take to make the SPA solution use the same Identity Model extension as the MVC template. I created a post that goes through the process that I went through. There is a link at the bottom to download the code from GitHub.

Spring MVC 3.0 - restrict what gets routed through the dispatcher servlet

I want to use Spring MVC 3.0 to build interfaces for AJAX transactions. I want the results to be returned as JSON, but I don't necessarily want the web pages to be built with JSP. I only want requests to the controllers to be intercepted/routed through the DispatcherServlet and the rest of the project to continue to function like a regular Java webapp without Spring integration.
My thought was to define the servlet-mapping url pattern in web.xml as being something like "/controller/*", then have the class level #RequestMapping in my controller to be something like #RequestMapping("/controller/colors"), and finally at the method level, have #RequestMapping(value = "/controller/colors/{name}", method = RequestMethod.GET).
Only problem is, I'm not sure if I need to keep adding "/controller" in all of the RequestMappings and no matter what combo I try, I keep getting 404 requested resource not available errors.
The ultimate goal here is for me to be able to type in a web browser "http://localhost:8080/myproject/controller/colors/red" and get back the RGB value as a JSON string.
You are not correct about needing to add the entire path everywhere, the paths are cumulative-
If you have a servlet mapping of /controller/* for the Spring's DispatcherServlet, then any call to /controller/* will be handled now by the DispatcherServlet, you just have to take care of rest of the path info in your #RequestMapping, so your controller can be
#Controller
#RequestMapping("/colors")
public class MyController{
#RequestMapping("/{name}
public String myMappedMethod(#PathVariable("name") String name, ..){
}
}
So now, this method will be handled by the call to /controller/colors/blue etc.
I don't necessarily want the web pages to be built with JSP
Spring MVC offers many view template integration options, from passthrough to raw html to rich templating engines like Velocity and Freemarker. Perhaps one of those options will fit what you're looking for.

Resources