Web API - 405 - The requested resource does not support http method 'PUT'

前端 未结 10 648
说谎
说谎 2020-12-01 14:10

I have a Web API project and I am unable to enable \"PUT/Patch\" requests against it.

The response I get from fiddler is:


HTTP/1.1 405 Method Not Al         


        
10条回答
  •  粉色の甜心
    2020-12-01 14:36

    Are you using attribute routing?

    This mystic error was a route attributes issue. This is enabled in your WebAPIConfig as:

     config.MapHttpAttributeRoutes(); 
    

    It turns out Web Api Controllers "cannot host a mixture of verb-based action methods and traditional action name routing. "; https://aspnetwebstack.codeplex.com/workitem/184

    in a nutshell: I needed to mark all of my actions in my API Controller with the [Route] attribute, otherwise the action is "hidden" (405'd) when trying to locate it through traditional routing.

    API Controller:

    [RoutePrefix("api/quotes")]
    public class QuotesController : ApiController
    {
        ...
    
        // POST api/Quote
        [ResponseType(typeof(Quote))]
        [Route]
        public IHttpActionResult PostQuote(Quote quote)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
    
            db.Quotes.Add(quote);
            db.SaveChanges();
    
            return CreatedAtRoute("", new { id = quote.QuoteId }, quote);
        }
    

    note: my Route is unnamed so the CreatedAtRoute() name is just an empty string.

    WebApiConfig.cs:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
        }
    }
    

    hope this helps

提交回复
热议问题