Umbraco ApiController actions wont map to http-verb - asp.net-web-api

I have been working some with the Web API before.. and as far as I can remember..
The actions in (at least the new version) is called Get,Post,Delete,Put etc...
and these actions are triggered depending of the http-verb in the request..
So for instance you might have an ApiController called UserApiController..
and if you do a request to /api/user with the POST http-verb.. then the Post-action in that controller will be triggered/executed..
However....
it seems like Im having some trouble with this using the UmbracoApiController... for some reason it wont execute post or get or any other action mapped to the http-verb..
Any ideas?.. is there any other way to sort of force a method to be executed depending on the http-verb?
My current code is:
public class MyController : UmbracoApiController
{
[HttpPost]
public bool Post()
{
return true;
}
}
I have placed a breakpoint with in the action..

The reason they won't be accepted is you're using the wrong attribute - HttpPost is part of the System.Web.Mvc namespace, whereas Web API is part of the System.Web.Http namespace.
You have to use AcceptVerbs("POST") instead.

Related

how to share the token between classes

I have having a design issue with asp.net web-api and would like to know how to solve this problem
public abstract class BaseApiController<TEntity> : ApiController where TEntity : Entity
{
protected string GetUsername()
{
return Utilities.GetUsername(Request.Headers.Authorization);
}
//some other code
}
public class StakeholderApiController : BaseApiController<Stakeholders>
{
ILogger _logger = new CustomApiLogger("StkhManager", GetUsername())
//some other code
}
now the problem I have is:
I have the BaseApiController which I am using the share certain functionality between all ApiControllers.
And then I have some specified ApiController for certain not shared functionality.
Now while doing logging, I do want to log the logged in user's name, the problem is I have to pass it everytime I create a new instance, is there a way I can make the logged in user's name global for the current api request so that it can be accessed everywhere.
I cannot make it static, otherwise for others request it will give wrong username.
is there a way I can avoid passing it everytime. Given that webapi is stateless, so session cant be used, is there anyother way??
I am using angularjs front end, hence I am NOT using any authorization technique provided by MVC/.net
Note:
I cannot move creation of Logger to base class for certain reasons
This is just one example, I want to use the logged in user's name in many other place. Hence dont want to pass it around.
There is a standard pattern in setting and accessing principal with ASP.NET Web API. From an ApiController such as your BaseApiController, you can just use the User property to retrieve the same. To set it, typically, the HttpRequestContext is obtained from the request object and the principal is set like so.
Request.GetRequestContext().Principal = new ClaimsPrincipal(...);
BTW, you can access the current request object in the Web API pipeline pretty much from anywhere.

Cancel long running requests in ASP .NET MVC 2

in my ASP .NET MVC2 application, there are two controller methods:
public class MyController : Controller{
public ActionResult Optimization(...){
//long running optimization
//this method writes to the Session
}
public void StopOptimization(){
//user wants to stop the optimization
//no access to Session needed
}
}
So in order to stop my long running optimization, the "Stop"-Method should be let through by ASP .NET MVC while the "Optimization"-Method is running.
I know that requests can be processed in parallel only if the SessionSate is at least set to "ReadOnly" for the whole controller class. I already followed the steps in this blog post.
However, this implies that data cannot be written to the Session anymore, which is required by the Optimization-Method.
For this reason, I have decided to remove the "Stop"-Method from this Controller and put it in an extra Controller, for which I set the SessionState to "ReadOnly":
...
using Microsoft.Web.Mvc;
...
[ControllerSessionState(ControllerSessionState.ReadOnly)]
public class StopController: Controller
{
public void Stop()
{
//Stop long running optimization
}
}
However, the Stop-Request is still only processed after the Optimization in the other controller is completed.
Additionally I tried to implement a custom controller factory that allows to define the session state for each ActionMethod separately - this is described here. This has not worked for me as I do not use ASP .NET MVC 3, but only ASP .NET MVC 2 in conjunction with the MVC Futures Library.
Does anyone have an idea how I can implement a Stop-Method that allows the user to stop my long running method from client-side?

MVC3 - Access User context in Controller base class

I have the following code in a view
#User.Identity.Name
Works fine.
The same code in a custom controller base class doesn't work. The User object is null
public class AdminBaseController : Controller
{
public AdminBaseController()
{
string userId = User.Identity.Name;
//if(!AnAdmin)
//redirect to UnauthorizedPage
I want to use this base class in place of System.Web.MVC.Controller as the base for all my Administration screens. This way I can redirect anybody that is not an admin (NTLM authentication).
Why the nulls? How do I get to my context? (HttpContext and something called ControllerContext are null too)
After some tinkering, things are null in the Controller constructors. The Action Methods work fine. Question still stands, but it appears I need help choosing an alternative implementation.
You should use Authorization filter, ASP.NET MVC Authorization. Also check Understanding Action Filters.
Or you can override Initialize method on Controller, User object will be initialized.
I just tried to access the 'Name'-property in a function within a controller class. That wasn't an issue and it wasn't null.
My best guess is that you can't access this object in the constructor of a controller.

Authorisation exceptions

I've tagged my controller with an authority annotation but would like to exempt one of the methods... can that be done? how?
[Authorize(Roles="Admin")]
public class ProductController : Controller
{
[DEAUTHORIZE]
public ActionResult Start(int it)
{ ... }
In MVC 4 was introduced AllowAnonymousAttribute which tells action invoker to skip AuthorizeAttribute.
[AllowAnonymous]
No, this can't be done. The standard way to achieve this is to simply move the Start action out in a separate controller. Another possibility consists into building a custom IFilterProvider which will apply the authorization attribute conditionally instead of baking it manually into the ProductController. For example NInject uses this and provides a pretty fluent syntax into configuring action filters. You can conditionally apply them based on the current context.

how to organize & implement jsp file structure using Spring

I'm a php programmer now doing a Java web project using Spring framework. I'm trying to organize my JSP files the way i would have organized my .tpl files in php.
So if it would have been php i would have done it like this:
index.tpl
includes one of layout.tpls (ajax.tpl, mobile.tpl, general.tpl, simplified.tpl . . .)
includes the header of the page
includes menus
includes the actual content of the page
includes the page footer
then from the php controller i would be able to do something like this:
setLayout('general');
showTopMenu(false);
setContent('mySexyPage');
beside that i would have organized my stuff so that my views (tpl files) will be organized in folderŅ‹ each corresponding to a single controller. like this:
userManager
addUSer.tpl
editUser.tpl
editUserPermissions.tpl
articleManager
addArticle.tpl
editArticle.tpl
and in each controller somehow define from which folder to load my content template.
Now in Spring i have a controller with methods handling requests and each of the methods returning what the view should be. I can extend all my controllers from a single abstract class where i will create an instance of ModelAndView with all default values set, then request handling methods will add what they need to the instance their daddy already created and return it.
The problem with the above approach is that i'm not forcing the coder who's writing controllers to use the ModelAndView object i created, he way still return anything he wants from the handling method he wrote.
Is there some interface containing a method like ModelAndView getModelAndView() my daddy controller will implement so Spring will ignore whatever handler methods are returning?
Or is there some better way to do this ?
Content Template Issue
The Java world has a (more than one actually, but I'm sticking with the one I know) solution for this problem, it is called Tiles. check out section 16 of the Spring 3.0.5 Reference.
ModelAndView Issue
This is more interesting. First, you can use Model with out view and have your controllers just return the view name (i.e. return a String). I believe you want to create the initial Model somewhere. Then have each controller hander method accept an argument of type Model.
Here is what I tend to do (no claim that it is a best practice):
Have a Controller.get(Model model) method that sets the initial values.
#RequestMapping(method = RequestMethod.GET)
public String get(Model model)
{ ... set default stuff ... }
Every Handler method is a variation of this:
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Model model, ... other stuff as needed ...)
{ ... set stuff in model ... }

Resources