HttpPostAttribute in ASP.NET MVC 2.0 Preview 1 Uses AcceptVerbsAttribute

If you want to limit the visibility on your actions based on an HTTP Get or HTTP Post in ASP.NET MVC 1.0, you typically used the AcceptVerbsAttribute and passed in the appropriate HTTP Verb as such:

 

[AcceptVerbs(HttpVerbs.Post)]

 

One of the new attributes that you will find in ASP.NET MVC 2.0 Preview 1 that acts as a shortcut to AcceptVerbs above is the HttpPostAttribute:

 

[HttpPost]

 

Nothing real exciting here as it is pretty simple to create your own attributes.

What I found interesting was that the HttpPostAttribute uses the AcceptVerbsAttribute internally. A quick view of the HttpPostAttribute in the ASP.NET MVC 2.0 Preview 1 Source Code shows the following:

 

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

public sealed class HttpPostAttribute : ActionMethodSelectorAttribute {

 

    private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Post);

 

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {

        return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);

    }

}

 

Of course, you could just as easily create an HttpGetAttribute using the same technique:

 

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

public sealed class HttpGetAttribute : ActionMethodSelectorAttribute {

 

    private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Get);

 

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {

        return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);

    }

}

 

We'll dive into some more interesting aspects of ASP.NET MVC 2.0 Preview 1 next time.

Check out ASP.NET MVC 2.0 Preview 1.

 

David Hayden

 

ASP.NET MVC Tutorials

 

posted on Thursday, August 06, 2009 11:21 AM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices