1

Is there any way to route based on the HTTP method specified in the request? I'm looking to have a GET and PUT at the same URI, but I can't seem to find the option to set the route between the two. The [HttpGet] and [HttpPut] attributes merely act as filters, so a PUT request is hitting the first action and erroring out with a 405 since it hits the GEt handler first.

What I want to do
~/User/PP GET -> UserController.GetPrivacyPolicy
~/User/PP PUT -> UserController.UpdateUserPrivacyPolicy

Whats currently happening
~/User/PP GET -> UserController.GetPrivacyPolicy
~/User/PP PUT -> UserController.GetPrivacyPolicy
(this errors out because i have a [HttpGet] filter on the GetPrivacyPolicy method)

Update: Just to compliment what was posted below, it looks like I misunderstood how the [HttpGet] and [HttpPut] attributes work, they ARE part of the routing process. I was able to achieve my desired result with the following

    [HttpGet]
    [Route("~/User/PP")]
    public string GetPrivacyPolicy()
    {
        return "Get PP";
    }
    [HttpPut]
    [Route("~/User/PP")]
    public void UpdatePrivacyPolicy()
    {
        return "Put PP";
    }

1 Answer 1

2

What you'll need to do is create your controller with identically named actions but decorated with different Http method attributes

public class UserController : Controller {

    [HttpGet]
    public ActionResult PrivacyPolicy(int id) {
        // Put your code for GetPrivacyPolicy here
    }

    [HttpPut]
    public ActionResult PrivacyPolicy(int id, YourViewModel model) {
        // Put your code for UpdatePrivacyPolicy here
    }

}

Of course there are appropriate actions for the other methods e.g. HttpPost, HttpDelete, HttpPatch.

Sign up to request clarification or add additional context in comments.

3 Comments

The attributes are only acting as filters, what you have done is overloaded the PrivacyPolicy method. I can do this, but I'm not actually passing in any paremeters to the action.
Ok wait, maybe I was wrong... The attributes DO act as part of the routing.
Yeah, they work a little differently to your normal overloaded method. Try POSTing with just an id and you'll get a nice little 404.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.