I have several ASP.NET WebApi controllers with some methods in each. All these methods should be accessible using HTTP POST only. What I'm trying to avoid is explicit [HttpPost] attribute usage for each method. Yep, I'm lazy.
My code looks like
[HttpPost]
public void Method1() { }
[HttpPost]
public void Method2() { }
...
Is there any way to configure route / base controller to access these methods via POST without setting attribute for each method? To have just like this
public void Method1() { }
public void Method2() { }
...
If I try to call method that doesn't have [HttpPost] I'm getting HTTP 405 error.
ASP.NET Web API uses convention over configuration. If you follow the convention to name your actions in the following way...
GetXXX
PostXXX
PutXXX
DeleteXXX
... you don't have to use the attributes. If the action starts with the appropriate HTTP verb Web API will take care of it.
Related
Hello I have added an extra get method in a API controller.
original Get
[HttpGet]
[Route("GetParticipants")]
public IActionResult GetParticipants([FromQuery] Guid conversationId, [FromQuery] ContextServiceModel context)
{
... stuff ...
}
New Get
[HttpGet]
[Route("GetThreadParticipants")]
public IActionResult ThreadParticipants([FromQuery] Guid parentMessageId)
{
... stuff ...
}
My question is does this follow Rest? Is it okay to route them this way and have different parameters?
You can have as many Action methods as you want in your controller until and unless no action methods have same routes.
Routing
Conventional Routing
Defined in WebAPI.config
Attribute Routing
Directly defined on action method
More on attribute routing
Attribute routing Web API's
What I basically want to know is this:
Suppose I have a method annotated with #RequestMapping and the value "/test/ajax". Can I make that specific method accessible only to internal calls but not to the client? If I run an ajax request on that url from within the server it should work normally, but if I run it directly from the browser it should return a 403.
Is that in any way possible?
add the spring annotation #CrossOrigin on controller layer for example
also, follow the given link https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
#CrossOrigin
#RestController
#RequestMapping("/account")
public class AccountController {
#GetMapping("/{id}")
public Account retrieve(#PathVariable Long id) {
// ...
}
#DeleteMapping("/{id}")
public void remove(#PathVariable Long id) {
// ...
}
}
If you allow only a method pass like this
#RestController
#RequestMapping("/account")
public class AccountController {
#CrossOrigin
#GetMapping("/{id}")
public Account retrieve(#PathVariable Long id) {
// ...
}
#DeleteMapping("/{id}")
public void remove(#PathVariable Long id) {
// ...
}
}
Is it possible to customize ASP.NET Web API's routing mechanism to route all requests to the API to one controller method?
If a request comes in to
www.mysite.com/api/products/
or
www.mysite.com/api/otherResource/7
All would be routed to my SuperDuperController's Get() method?
I ran into a case where I needed to do this. (Web API 2)
I first looked into creating custom IHttpControllerSelector and IHttpActionSelectors. However, that was a bit of a murky way around. So I finally settled on this dead simple implementation. All you have to do is setup a wildcard route. Example:
public class SuperDuperController : ApiController
{
[Route("api/{*url}")]
public HttpResponseMessage Get()
{
// url information
Request.RequestUri
// route values, including "url"
Request.GetRouteData().Values
}
}
Any GET request that starts with "api/" will get routed to the above method. That includes the above mentioned URLs in your question. You will have to dig out information from the Request or context objects yourself since this circumvents automatic route value and model parsing.
The good thing about this is you can still use other controllers as well (as long as their routes don't start with "api/").
I don't konw why you would want to do this and I certainly wouldn't recommend routing everything through one controller, however you could achieve this as follows. Assuming you are only ever going to have a resource with an optional id in your calls, add this to your WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{resource}/{id}",
defaults: new { controller = "SuperDuper", id = RouteParameter.Optional }
);
}
}
Then define your controller method as follows:
public class SuperDuperController : ApiController
{
public IHttpActionResult Get(string resource, int? id = null)
{
return Ok();
}
}
You would need to decide on an appropriate IHttpActionResult to return for each different type of resource.
Alternatively using Attribute Routing, ensure that config.MapHttpAttributeRoutes() is present in your WebApiConfig and add the following attributes to your controller method:
[RoutePrefix("api")]
public class SuperDuperController : ApiController
{
[Route("{resource}/{id?}")]
public IHttpActionResult Get(string resource, int? id = null)
{
return Ok();
}
}
I used to use javax.servlet.Filter to handle some process such as authentication and character encoding. Is there something in Spring MVC 3.0 like Filter, handling request before other controllers handle it.(a front controller) And also, it is able to be injected the dependencies by constructor or setters. For example,
#Controller
public class HomeController {
#RequestMapping("/home")
public String getHomePage() {
return "home";
}
}
public class Authentication {
private Foo foo;
public void setFoo(Foo foo) {
this.foo = foo;
}
// filter the url "/home"
public String authenticate() {
if (foo.authenticated()) {
return toHomeController;
}
return toErrorController;
}
}
Before handling the request from /home or other urls, the user should be authorized. If not, he should be redirected to other url, such as /error.
I used to use javax.servlet.Filter to handle some process such as authentication and character encoding.
All of this already exists in Spring:
use Spring Security for authentication/authorization
use CharacterEncodingFilte for character encoding
Is there something in Spring MVC 3.0 like Filter, handling request before other controllers handle it.(a front controller)
Yes, Spring has DispatcherServlet who does exactly this.
And also, it is able to be injected the dependencies by constructor or setters.
Yes, Spring will do it for you.
You can start from Spring Reference:
Read about Spring IoC
Read about Web MVC framework
I've been working on a rather large web application that requires a specific id param in the url for every page visited (for example, /controller/action/id?AccountId=23235325). This id has to be verified every time someone visits a page.
I want to reduce code replication as much as possible, and was wondering if there is a way to use an init method or constructor in a controller that inherits the MVC controller, and then have that controller extended by the others.
I'm using ASP.NET MVC 2.
Yes this is possible using either a base controller class that all your controllers inherit or by creating a custom attribute that you decorate your controller with.
Base controller:
public class BaseController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
// verify logic here
}
}
Your controllers:
public class AccountController : BaseController
{
// the Initialize() function will get called for every request
// thus running the verify logic
}
Custom Authorization Attribute:
public class AuthorizeAccountNumberAttribute : AuthorizationAttribute
{
protected override AuthorizationResult IsAuthorized(System.Security.Principal.IPrincipal principal, AuthorizationContext authorizationContext)
{
// verify logic here
}
}
On your controller(s):
[AuthorizeAccountNumber]
public class AccountController : Controller
{
// the IsAuthorized() function in the AuthorizeAccountNumber will
// get called for every request and thus the verify logic
}
You can combine both approaches to have another custom base controller class which is decorated with the [AuthorizeAccountNumber] which your controllers that require verification inherit from.