ASP.NET MVC 5 routing, hide data in URL - asp.net-mvc

I have two types of functionality for a action with a bool variable.
[HttpGet]
public ActionResult action(bool data = false)
{
if(data == false)
{
return View("view1");
}
else
{
return View("view2");
}
}
It is a [httpGet] method. some link has data bool value as true and some has false.
The url has the attribute like http://localhost:58241/action?data=False
I want to hide the ?data=False or ?data=Truefrom URL and should possess all the same functionality like before.
I want the URL like http://localhost:58241/action
Thanks in advance.

Routing has absolutely nothing at all to do with query string parameters. And in any case, you still need to transfer the data parameter to the server for the action method to receive it. There are 3 ways to do this:
Pass it in the URL using HTTP GET (as a route value or query string value)
Pass it in the form body using HTTP POST
Pass it in a model (using HTTP POST and model binding)
The simplest option is #1, however since you mentioned this isn't acceptable to pass the data through the URL, your only choice is to use HTTP post. So, the rest of this answer uses #2.
First, the default route does not cover your choice of URL (/action), so you need to insert a custom route for this.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Add route to handle /action
routes.MapRoute(
name: "Action",
url: "action",
defaults: new { controller = "Data", action = "Action" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Next, you need a controller to handle both the GET and POST from the browser.
public class DataController : Controller
{
public ActionResult Action()
{
return View();
}
[HttpPost]
public ActionResult Action(bool data = false)
{
if (data)
{
return View("view2");
}
return View("view1");
}
}
The data is sent back to the server in the POST, so it is not required to pass it in the URL.
Finally, you have the view (named Action.cshtml) that is returned from the Action action method. It has 2 different form tags that submit a different value for data depending on the button clicked.
#{
ViewBag.Title = "Action";
}
<h2>Choose an Option</h2>
#using (Html.BeginForm("action", "Data")) {
<input type="hidden" name="data" value="true" />
<input type="submit" value="With Data" />
}
#using (Html.BeginForm("action", "Data")) {
<input type="hidden" name="data" value="false" />
<input type="submit" value="Without Data" />
}
Note that you could do this step entirely in JavaScript (AJAX POST) if you please, which would enable you to use a hyperlink instead of a button or you could just style the button using CSS to look like a hyperlink.

You can achieve this functionality partially by making the parameter optional as suggested by #VishalSuthar. But for one condition you must use the parameter if you want to access it using a GET request.
Else, if you make the Action only accessible by POST requests, this part will be easier to implement. In that case only change you need is :
[HttpPost]
public ActionResult action(bool data = false)
{
if(data == false)
{
return View("view1");
}
else
{
return View("view2");
}
}
This way you can pass the parameter in form and hit the action with the URL showing: http://localhost:58241/action
Note: This way the action will not be accessible via GET requests.

Related

Why logoff user not working?

I want to make log off user functionality.
When user click this linq:
<a tabindex="-1" href="javascript:document.getElementById('logoutForm').submit()"><i class="glyphicon glyphicon-off"></i>LogOff </a>
This action is called:
[Authorize]
public class AccountController : BaseController
{
// POST: /Account/LogOff
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
}
While I chenge the linq above to this:
#Ajax.ActionLink(#Resources.Resources.LogOff, "LogOff", "Account", new { id = "logoutForm" }, new AjaxOptions { HttpMethod = "POST" })
I get error:
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly. Requested URL:
/MySiteName/Account/LogOff/logoutForm
Any idea why the second attitude dosent work?Why I get logoutForm as postfix in my URL?
The route for /MySiteName/Account/LogOff/logoutForm simply does not exist. You are passing in a route parameter id with the value "logoutForm" to your route, yet the action method LogOff does not accept any parameters.
This is also excactly what the error tells you. You can verify this by looking at the signature of your action method:
public ActionResult LogOff() {}
As you can see it does not take any parameters, so the url you have to call is the same as it states in the comment just above it: // POST: /Account/LogOff
That in turn means, removing your route parameters, so just replace new { id = "logoutForm" } with null:
#Ajax.ActionLink(#Resources.Resources.LogOff, "LogOff", "Account", null, new AjaxOptions { HttpMethod = "POST" })
And you should be good to go.
I do not see a reason, why the Log out itself should be a post. You are not submitting any data to the server. You can do a simple GET, achieve the same and remove some unnessecary complexity along the way.

I'm not getting friendly url in a form with GET method

I setup a route like that:
routes.MapRoute(
name: "Pesquisar",
url: "Pesquisar/{aaa}/{bbb}/{id}",
defaults: new { controller = "Home", action = "Pesquisar",
aaa = UrlParameter.Optional,
bbb = UrlParameter.Optional,
id = UrlParameter.Optional
}
);
When I press Send button in a form (with GET method) the url is like that:
http://localhost:00000/Pesquisar?aaa=One&bbb=Two
But I was expecting for:
http://localhost:00000/Pesquisar/One/Two
When you map a rout, it adds it to the end of a list. When the router looks for the rule to match, it starts at the begining of the list and itterates through it. It will take the first rule that matches, not the most specific rule. Because it is natural to append code to the end, the default rule (which works for almost everything) will be at the start.
Try re-ordering your code to look like this:
///The specific rout which you want to use
routes.MapRoute(
name: "Pesquisar",
url: "{action}/{aaa}/{bbb}/{id}",
defaults: new { controller = "Home", action = "Pesquisar",
aaa = UrlParameter.Optional,
bbb = UrlParameter.Optional,
id = UrlParameter.Optional
}
);
///The generic catch all router
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
More information can be found in this question:
Setting up ASP.Net MVC 4 Routing with custom segment variables
When I press Send button in a form (with GET method) the url is like that:
http://mydomain.com/Pesquisar?aaa=One&bbb=Two
But I was expecting for:
http://mydomain.com/One/Two
This is because the browser is unaware of the fancy url you want, as the standard form Get method is to append form values in the querystring.
What you mostly likely have to do is something like Creating Canonical URLs including an id and title slug, except redirect to the url you want if it's not the url you want to display.
Or you can use jQuery to manually create the url you want on submit, but requires more client side work.
Not sure if you get a clean URL directly from a html form GET.
One suggestion would be to POST it to an action, do what you need to do with the data, then on completion, redirect to your clean URL.
e.g.
ViewModel:
public sealed class PesquisarModel
{
public string aaa { get; set; }
public string bbb { get; set; }
public string id { get; set; }
}
Controller Actions:
[HttpGet]
public ActionResult Pesquisar(PesquisarModel m)
{
return View();
}
[HttpPost]
[ActionName("Pesquisar")]
public ActionResult PesquisarPost(PesquisarModel m)
{
//do stuff
return RedirectPermanent("/pesquisar/" + m.aaa + "/" + m.bbb + "/" + m.id);
}
View:
#model MyApplication.Models.PesquisarModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.aaa)
#Html.TextBoxFor(m => m.bbb)
#Html.TextBoxFor(m => m.id)
<button type="submit">Submit</button>
}
This is the browser behavior. When making a GET request browser appends all KeyValue pairs to querystring.
The mentioned route format will be available, when we use Html.ActionLink or Html.RouteUrl etc.
You could probably write few code in OnActionExecuting ( or you can use any handler) to reconstruct RouteData and redirect with appropriate url. Below code is not tested
var queries = this.Request.QueryString;
foreach(var query in queries)
{
// Add/Update to RequestContext.RouteData
}
var redirectUrl = Url.RouteUrl("Pesquisar",this.RequestContext.RouteData);
Response.Redirect(redirectUrl);
That's expected behavior.
The routing system is on server side. The browser knows nothing about routes, and what you're doing happens in the browser.
If you want to get that route you have to compose it on the client side with a custom script which uses the <form>'s action, an the values of the <input type="text"> values.
You cannot generate the Url on the server side (which could be done with some UrlHelper extension methods) because the changes on the text boxes wouldn't be updated.
This is not advisable because if you make changes on the routes, you could forget to update them in your browser scripts, breaking you application.
You could avoid this problem by creating the url in the server side using an UrlHelper extension method with special placeholders, which could be easily replaced on the client side. I.e. generate an url like this:
http://localhost/Pesquisar/$aaa$/$bbb$/$id$
by providing RouteValues like this: new {aaa="$aaa$, bbb="$bbb$, id="$id$"} to an UrlHelper method. This url can be stored in the value property of a hidden field.
Then, make a browser script for the click event of your button, recover the url with the placeholders from the hidden field, and replace the placeholders with the actual values of the textboxes. To execute the get run this: document.location = theUrl;
If you want to d this for many differnt instances you could create a Helper to geenrate the hidden field with the Url, and a javascript which makes the replacements.
The question is... is it worth the effort?

Passing an url as parameter to controller action

On my asp.net mvc page I need to render multiple images that are stored on third-party images hosting service. The service has some api which returns me a list of image urls.
In *.cshtml file a have the fallowing html markup:
#foreach (var img in Model.Images)
{
<img src="#img.ImageUrl" />
}
It's works perfectly. But for some reason I can't use direct URL to the image in the "src" attribute. Next, I have created new async controller that should return an image:
public class ImagesController : AsyncController
{
//
// GET: /Images/
public void GetImageAsync(string url)
{
AsyncManager.OutstandingOperations.Increment();
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
AsyncManager.Parameters["response"] = response;
AsyncManager.OutstandingOperations.Decrement();
}
public FileResult GetImageCompleted(WebResponse response)
{
return base.File(response.GetResponseStream(), response.ContentType);
}
}
Now I need to pass a full image url to my controller action.
Something like this:
#foreach (var img in Model.Images)
{
<img src="Images/GetImage/**#img.ImageUrl**" />
}
how to create a new route for passing this parameter to action?
Thanks!
You mean this?
routes.MapRoute(
"GetImage",
"Images/GetImage/{*url}",
new { controller = "Images", action = "GetImageAsync" }
);
I'm not sure why you need all that though. An AsyncController + routing in order to fetch all image url's seems to be overkill...

Asp.net MVC ModelState.Clear

Can anyone give me a succinct definition of the role of ModelState in Asp.net MVC (or a link to one). In particular I need to know in what situations it is necessary or desirable to call ModelState.Clear().
Bit open ended huh... sorry, I think it might help if tell you what I'm acutally doing:
I have an Action of Edit on a Controller called "Page". When I first see the form to change the Page's details everything loads up fine (binding to a "MyCmsPage" object). Then I click a button that generates a value for one of the MyCmsPage object's fields (MyCmsPage.SeoTitle). It generates fine and updates the object and I then return the action result with the newly modified page object and expect the relevant textbox (rendered using <%= Html.TextBox("seoTitle", page.SeoTitle)%>) to be updated ... but alas it displays the value from the old model that was loaded.
I've worked around it by using ModelState.Clear() but I need to know why / how it has worked so I'm not just doing it blindly.
PageController:
[AcceptVerbs("POST")]
public ActionResult Edit(MyCmsPage page, string submitButton)
{
// add the seoTitle to the current page object
page.GenerateSeoTitle();
// why must I do this?
ModelState.Clear();
// return the modified page object
return View(page);
}
Aspx:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyCmsPage>" %>
....
<div class="c">
<label for="seoTitle">
Seo Title</label>
<%= Html.TextBox("seoTitle", page.SeoTitle)%>
<input type="submit" value="Generate Seo Title" name="submitButton" />
</div>
I think is a bug in MVC. I struggled with this issue for hours today.
Given this:
public ViewResult SomeAction(SomeModel model)
{
model.SomeString = "some value";
return View(model);
}
The view renders with the original model, ignoring the changes. So I thought, maybe it does not like me using the same model, so I tried like this:
public ViewResult SomeAction(SomeModel model)
{
var newModel = new SomeModel { SomeString = "some value" };
return View(newModel);
}
And still the view renders with the original model. What's odd is, when I put a breakpoint in the view and examine the model, it has the changed value. But the response stream has the old values.
Eventually I discovered the same work around that you did:
public ViewResult SomeAction(SomeModel model)
{
var newModel = new SomeModel { SomeString = "some value" };
ModelState.Clear();
return View(newModel);
}
Works as expected.
I don't think this is a "feature," is it?
Update:
This is not a bug.
Please stop returning View() from a POST action. Use PRG instead and redirect to a GET if the action is a success.
If you are returning a View() from a POST action, do it for form validation, and do it the way MVC is designed using the built in helpers. If you do it this way then you shouldn't need to use .Clear()
If you're using this action to return ajax for a SPA, use a web api controller and forget about ModelState since you shouldn't be using it anyway.
Old answer:
ModelState in MVC is used primarily to describe the state of a model object largely with relation to whether that object is valid or not. This tutorial should explain a lot.
Generally you should not need to clear the ModelState as it is maintained by the MVC engine for you. Clearing it manually might cause undesired results when trying to adhere to MVC validation best practises.
It seems that you are trying to set a default value for the title. This should be done when the model object is instantiated (domain layer somewhere or in the object itself - parameterless ctor), on the get action such that it goes down to the page the 1st time or completely on the client (via ajax or something) so that it appears as if the user entered it and it comes back with the posted forms collection. Some how your approach of adding this value on the receiving of a forms collection (in the POST action // Edit) is causing this bizarre behaviour that might result in a .Clear() appearing to work for you. Trust me - you don't want to be using the clear. Try one of the other ideas.
If you want to clear a value for an individual field then I found the following technique useful.
ModelState.SetModelValue("Key", new ValueProviderResult(null, string.Empty, CultureInfo.InvariantCulture));
Note:
Change "Key" to the name of the field that you want to reset.
Well lots of us seem to have been bitten by this, and although the reason this happens makes sense I needed a way to ensure that the value on my Model was shown, and not ModelState.
Some have suggested ModelState.Remove(string key), but it's not obvious what key should be, especially for nested models. Here are a couple methods I came up with to assist with this.
The RemoveStateFor method will take a ModelStateDictionary, a Model, and an expression for the desired property, and remove it. HiddenForModel can be used in your View to create a hidden input field using only the value from the Model, by first removing its ModelState entry. (This could easily be expanded for the other helper extension methods).
/// <summary>
/// Returns a hidden input field for the specified property. The corresponding value will first be removed from
/// the ModelState to ensure that the current Model value is shown.
/// </summary>
public static MvcHtmlString HiddenForModel<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
RemoveStateFor(helper.ViewData.ModelState, helper.ViewData.Model, expression);
return helper.HiddenFor(expression);
}
/// <summary>
/// Removes the ModelState entry corresponding to the specified property on the model. Call this when changing
/// Model values on the server after a postback, to prevent ModelState entries from taking precedence.
/// </summary>
public static void RemoveStateFor<TModel, TProperty>(this ModelStateDictionary modelState, TModel model,
Expression<Func<TModel, TProperty>> expression)
{
var key = ExpressionHelper.GetExpressionText(expression);
modelState.Remove(key);
}
Call from a controller like this:
ModelState.RemoveStateFor(model, m => m.MySubProperty.MySubValue);
or from a view like this:
#Html.HiddenForModel(m => m.MySubProperty.MySubValue)
It uses System.Web.Mvc.ExpressionHelper to get the name of the ModelState property.
Well the ModelState basically holds the current State of the model in terms of validation, it holds
ModelErrorCollection: Represent the errors when the model try to bind the values.
ex.
TryUpdateModel();
UpdateModel();
or like a parameter in the ActionResult
public ActionResult Create(Person person)
ValueProviderResult: Hold the details about the attempted bind to the model.
ex. AttemptedValue, Culture, RawValue.
Clear() method must be use with caution because it can lead to unspected results. And you will lose some nice properties of the ModelState like AttemptedValue, this is used by MVC in the background to repopulate the form values in case of error.
ModelState["a"].Value.AttemptedValue
I had an instance where I wanted to update the model of a sumitted form, and did not want to 'Redirect To Action' for performanace reason. Previous values of hidden fields were being retained on my updated model - causing allsorts of issues!.
A few lines of code soon identified the elements within ModelState that I wanted to remove (after validation), so the new values were used in the form:-
while (ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")).Value != null)
{
ModelState.Remove(ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")));
}
I wanted to update or reset a value if it didn't quite validate, and ran into this problem.
The easy answer, ModelState.Remove, is.. problematic.. because if you are using helpers you don't really know the name (unless you stick by the naming convention). Unless perhaps you create a function that both your custom helper and your controller can use to get a name.
This feature should have been implemented as an option on the helper, where by default is does not do this, but if you wanted the unaccepted input to redisplay you could just say so.
But at least I understand the issue now ;).
Got it in the end. My Custom ModelBinder which was not being registered and does this :
var mymsPage = new MyCmsPage();
NameValueCollection frm = controllerContext.HttpContext.Request.Form;
myCmsPage.SeoTitle = (!String.IsNullOrEmpty(frm["seoTitle"])) ? frm["seoTitle"] : null;
So something that the default model binding was doing must have been causing the problem. Not sure what, but my problem is at least fixed now that my custom model binder is being registered.
Generally, when you find yourself fighting against a framework standard practices, it is time to reconsider your approach. In this case, the behavior of ModelState. For instance, when you don't want model state after a POST, consider a redirect to the get.
[HttpPost]
public ActionResult Edit(MyCmsPage page, string submitButton)
{
if (ModelState.IsValid) {
SomeRepository.SaveChanges(page);
return RedirectToAction("GenerateSeoTitle",new { page.Id });
}
return View(page);
}
public ActionResult GenerateSeoTitle(int id) {
var page = SomeRepository.Find(id);
page.GenerateSeoTitle();
return View("Edit",page);
}
EDITED to answer culture comment:
Here is what I use to handle a multi-cultural MVC application. First the route handler subclasses:
public class SingleCultureMvcRouteHandler : MvcRouteHandler {
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var culture = requestContext.RouteData.Values["culture"].ToString();
if (string.IsNullOrWhiteSpace(culture))
{
culture = "en";
}
var ci = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
return base.GetHttpHandler(requestContext);
}
}
public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var culture = requestContext.RouteData.Values["culture"].ToString();
if (string.IsNullOrWhiteSpace(culture))
{
culture = "en";
}
var ci = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
return base.GetHttpHandler(requestContext);
}
}
public class CultureConstraint : IRouteConstraint
{
private string[] _values;
public CultureConstraint(params string[] values)
{
this._values = values;
}
public bool Match(HttpContextBase httpContext,Route route,string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"
string value = values[parameterName].ToString();
// Return true is the list of allowed values contains
// this value.
return _values.Contains(value);
}
}
public enum Culture
{
es = 2,
en = 1
}
And here is how I wire up the routes. After creating the routes, I prepend my subagent (example.com/subagent1, example.com/subagent2, etc) then the culture code. If all you need is the culture, simply remove the subagent from the route handlers and routes.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("Content/{*pathInfo}");
routes.IgnoreRoute("Cache/{*pathInfo}");
routes.IgnoreRoute("Scripts/{pathInfo}.js");
routes.IgnoreRoute("favicon.ico");
routes.IgnoreRoute("apple-touch-icon.png");
routes.IgnoreRoute("apple-touch-icon-precomposed.png");
/* Dynamically generated robots.txt */
routes.MapRoute(
"Robots.txt", "robots.txt",
new { controller = "Robots", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Sitemap", // Route name
"{subagent}/sitemap.xml", // URL with parameters
new { subagent = "aq", controller = "Default", action = "Sitemap"}, new[] { "aq3.Controllers" } // Parameter defaults
);
routes.MapRoute(
"Rss Feed", // Route name
"{subagent}/rss", // URL with parameters
new { subagent = "aq", controller = "Default", action = "RSS"}, new[] { "aq3.Controllers" } // Parameter defaults
);
/* remap wordpress tags to mvc blog posts */
routes.MapRoute(
"Tag", "tag/{title}",
new { subagent = "aq", controller = "Default", action = "ThreeOhOne", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler(); ;
routes.MapRoute(
"Custom Errors", "Error/{*errorType}",
new { controller = "Error", action = "Index", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
);
/* dynamic images not loaded from content folder */
routes.MapRoute(
"Stock Images",
"{subagent}/Images/{*filename}",
new { subagent = "aq", controller = "Image", action = "Show", id = UrlParameter.Optional, culture = "en"}, new[] { "aq3.Controllers" }
);
/* localized routes follow */
routes.MapRoute(
"Localized Images",
"Images/{*filename}",
new { subagent = "aq", controller = "Image", action = "Show", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
"Blog Posts",
"Blog/{*postname}",
new { subagent = "aq", controller = "Blog", action = "Index", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
"Office Posts",
"Office/{*address}",
new { subagent = "aq", controller = "Offices", action = "Address", id = UrlParameter.Optional }, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { subagent = "aq", controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "aq3.Controllers" } // Parameter defaults
).RouteHandler = new MultiCultureMvcRouteHandler();
foreach (System.Web.Routing.Route r in routes)
{
if (r.RouteHandler is MultiCultureMvcRouteHandler)
{
r.Url = "{subagent}/{culture}/" + r.Url;
//Adding default culture
if (r.Defaults == null)
{
r.Defaults = new RouteValueDictionary();
}
r.Defaults.Add("culture", Culture.en.ToString());
//Adding constraint for culture param
if (r.Constraints == null)
{
r.Constraints = new RouteValueDictionary();
}
r.Constraints.Add("culture", new CultureConstraint(Culture.en.ToString(), Culture.es.ToString()));
}
}
}
Well, this seemed to work on my Razor Page and never even did a round trip to the .cs file.
This is old html way. It might be useful.
<input type="reset" value="Reset">

What are the ActionResult AcceptVerbsAttribute default HTTP methods?

I know you can restrict which HTTP methods a particular ActionResult method responds to by adding an AcceptVerbsAttribute, e.g.
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
...
}
But I was wondering: which HTTP methods an ActionResult method will accept without an explicit [AcceptVerbs(...)] attribute?
I would presume it was GET, HEAD and POST but was just wanting to double-check.
Thanks.
Without AcceptVerbsAttribute your Action will accept requests with any HTTP methods. BTW you can restrict HTTP methods in your RouteTable:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new { HttpMethod = new HttpMethodConstraint(
new[] { "GET", "POST" }) } // Only GET or POST
);
It will accept all HTTP methods.
Look at slightly formatted fragment from ActionMethodSelector.cs (ASP.NET MVC source could be downloaded here):
private static List<MethodInfo> RunSelectionFilters(ControllerContext
controllerContext, List<MethodInfo> methodInfos)
{
// remove all methods which are opting out of this request
// to opt out, at least one attribute defined on the method must
// return false
List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();
List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>();
foreach (MethodInfo methodInfo in methodInfos)
{
ActionMethodSelectorAttribute[] attrs =
(ActionMethodSelectorAttribute[])methodInfo.
GetCustomAttributes(typeof(ActionMethodSelectorAttribute),
true /* inherit */);
if (attrs.Length == 0)
{
matchesWithoutSelectionAttributes.Add(methodInfo);
}
else
if (attrs.All(attr => attr.IsValidForRequest(controllerContext,
methodInfo)))
{
matchesWithSelectionAttributes.Add(methodInfo);
}
}
// if a matching action method had a selection attribute,
// consider it more specific than a matching action method
// without a selection attribute
return (matchesWithSelectionAttributes.Count > 0) ?
matchesWithSelectionAttributes :
matchesWithoutSelectionAttributes;
}
So if there is no better matching action method with explicit attribute, action method without attributes will be used.

Resources