Any way to handle Put and Delete verbs in ASP.Net MVC? - asp.net-mvc

just wondering if anyone knows of a truly restful Put/delete implementation asp.net mvc preview 5 preferably.

Check out the mvccontrib project at http://www.mvccontrib.org.
In the source code a restful implementation has been added and it is current up to Preview 5. Check out the source code here - http://mvccontrib.googlecode.com/svn/trunk/src/MVCContrib/SimplyRestful

Rails uses a "method" parameter in the form and then fakes it, but calls the appropriate method if you designate it.
I understand most clients won't support restful stack, but can asp.net mvc, auto-negotiate these verbs and place them in the appropriately deemed actions?

I've been covering this in my blog http://shouldersofgiants.co.uk/blog/ where I'm looking at an entire RESTful web service based on ASP.Net and MVC

I don't know of one off the top of my head, but you might look into the way that Rails handles it if you don't find anything else, and try porting it over. Rails utilizes POST, GET, PUT, and DELETE, but it apparently has to do some fakery for PUT. Could be worth looking into if you come up dry here.

I think that the new AcceptVerbsAttribute in preview 5 should be capable of directing any type of request to a designated action. Marking a method like below in theory allows handling of all verbs but I haven't explicitly tested put or delete.
[AcceptVerbs("delete")]
public object DoDeleteAction()

With MVC Beta, u can now use an HttpVerbs enumeration.
here's an example...
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{ ... }
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update()
{ ... }
[AcceptVerbs(HttpVerbs.Delete)]
public ActionResult Delete()
{ ... }
you get the idea.
hth :)

Related

Why shouldn't I use attribute routing in a traditional (non API) controller?

I've been using attribute based routing in an API controller project:
[HttpGet("products/{productId}")]
public async Task<IActionResult> ProductDetails(int productId) {
...
return Ok(someModelToSerializeAsJson)
}
This works great. I find it much clearer and less error prone than conventional route table based routing. I kept wondering why we can't use attribute based routing for MVC (non API) projects with views. I tried this for a small non public facing web application and it seems to work great. You have to mark the controllers as [ApiController], but you can still return views in the action methods.
[HttpGet("products/{productId}")]
public async Task<IActionResult> ProductDetails(int productId) {
...
return View(someModelForTheView)
}
I would like to make the same choice for our main public facing website, but I'm worried I'm missing a solid reason why I shouldn't.
As an example, I've noticed that API controllers aggressively turn off HTTP caching (e.g. cache-control: no-cache, no-store). That is a quirky issue to work around.
Are there other clear reasons to NOT use attribute based routing with MVC views?
Looks like I was wrong. You can use attribute based routing for regular MVC controllers. I thought you had to use an ApiController, but that is not correct. The trick for me was that the base class for my controller needed to be Controller instead of BaseController. Shout out to #Métoule for that nugget of information.

Greedy segment with .NET MVC 5 Attribute Routing

I would like to define a route as follows -
[Route("clients/{*code}/{id:guid}/update")]
public ActionResult Update(string code, Guid id)
{
}
Code will be something like "foo/bar/xyz".
Unfortunately, out-of-the-box MVC doesn't support greedy parameters in the middle of a Route definition.
This has previously been solved using the old MVC routing conventions, however I would like to have this as a RouteAtribute defintion.
As far as I know you cannot do it directly. However, you should be able to use IIS module UrlRewrite and rewrite the query with a greedy parameter in the middle to the one with a greedy parameter at the end.
So a client queries: clients/{*code}/{id:guid}/update
and your web api sees clients/{id:guid}/update/{*code}
From what I can tell there is no out-of-the-box way of doing this other than to use custom code like this example. Hope it helps.

No HTTP requests for certain controller methods

I'm currently reading a book about ASP.NET MVC3 to learn working with this framework. The concept of partial views is explained and altough it's an easy concept, I have a small question with it.
This razor code is added to the view:
#{ Html.RenderAction("Summary", "Cart"); }
This calls the Summary()-method on the CartController. The problem is: as a user, I can call this method via a HTTP request (GET/POST,...) what shouldn't be possible.
I know there are attributes like [HttpPost] and [HttpGet] to permit only certain sorts of HTTP requests, but is there also an attribute to prevent these? Also, where can I find a list of available attributes?
Thanks
If you have a partial view, you are right that it has to be a public method but it should not be addressable on its own. to achive this you can decorate the action method with the [ChildActionOnly]
See this for details
http://msdn.microsoft.com/en-us/library/system.web.mvc.childactiononlyattribute.aspx
And for a list of similar attributes:
http://msdn.microsoft.com/en-us/library/system.web.mvc.filterattribute.aspx

Creating an API with ASP.NET MVC - All in one project, or two projects?

So I've recd. a requirement to create an API to access our application. Not all controller actions are covered by the API (maybe 50%).
I figure I can either use the same project, check the http headers for each request and respond with either xml, JSON or html as required (much like rails).
OR
Create a new ASP.NET MVC application, deploy # api.myapp.com and use it exclusively for API access.
I assume I could write a base controller for the first option to handle 99% of the work. The issue with the first option is we don't need (or want) API functionality for at least 1/2 of controller actions (and prob. never will).
In the second option I have a duplicate of some controllers, but the good news is most/all? my controller actions are only a couple lines of code. Typically:
Whatever whatever = new Whatever(....);
repository.Save(whatever);
Anyway, what do the stack overflowers think?
It seems that you want to create something like REST service. Please have a look at this post of Phil Haack.
Yes, I'm sure you can put it in the same project. But it will be better to separate them in some way (using areas from MvcContrib or move controllers of api and web application to separate assemblies like this done in SharpArchitecture. If your controllers duplicate a lot of code you may create generic controller like:
public class ControllerBase<T, Service> : Controller
where Service : IService<T>
{
public Service service { get; set; }
public ActionResult Save(int id)
{
var item = service.Get(id);
if (TryUpdateModel<T>(item))
{
service.Save(item);
return View("Success");
}
return View("Error", item);
}
}
Hope this helps.
I think I'd put in the same project, but segregate it using separate routes.
API: http://example.com/api/widget/list
App: http://example.com/widget/list
You could then reuse as much code as possible -- push the data selection and other code into your BLL, for instance. Keeping it in the same project will make it easier to use your API code via AJAX from the client.
I think putting the same code in 2 different projects is asking for trouble in the long run.
Put it all in the same project.
If you need some seperation between regular vs API requests you can use seperate routes.
You can then make a private function that does the action and just have the public facing one decide to render in html or JSON/XML

Tweaking asp.net mvc

I really love the "one model in - one model out" idea of Fubu MVC. A controller would look something like this
public class MyController
{
public OutputModel MyAction(InputModel inputModel)
{
//..
}
}
and the service locator would automagically fill in all the required dependencies in the constructor.
This makes the controller very easy to test.
So my question is: How would you go about tweaking asp.net mvc to allow this simplicity in the controllers ?
What you're looking for the is the ControllerActionInvoker. You'll have to implement your own and override/take over handling a lot of the pipeline work that ASP.NET MVC.
For reference, check out Jonathon Carter's 2-part post on doing ControllerActionInvokers:
http://lostintangent.com/2008/07/03/aspnet-mvc-controlleractioninvoker-part-1/
and
http://lostintangent.com/2008/07/07/aspnet-mvc-controlleractioninvoker-part-2/
Also, the Oxite team did this in the 2nd release of Oxite, you can check out their source here:
http://oxite.codeplex.com/SourceControl/changeset/view/30544
Here's a link directly to their ControllerActionInvoker implementation:
http://oxite.codeplex.com/SourceControl/changeset/view/30544#442766
Never really dug deep inside ASP.NET MVC internals, but I guess custom ModelBinder and ActionResult will do the job.

Resources