【问题标题】:MVC Api Controller Method HttpPost not workingMVC Api 控制器方法 HttpPost 不起作用
【发布时间】:2017-08-08 18:40:09
【问题描述】:

我正在使用 Visual Studio 2013...

我在使用 Api 控制器方法时遇到了一些问题。

我了解HTTPGETHTTPPUT[FromUri][FromBody]. 之间的区别

我有一个简单的方法,我正在测试所有组合。

当我跑步时

http://localhost:62536/api/Controller/Method/10

I Got HTTP 404 error is this examples

[HttpPut]
public string Method([FromUri] int a)
{
return "";
}

[HttpPut]
public string Method( int a)
{
return "";
}

[HttpGet]
public string Method([FromUri] int a)
{
return "";
}

[HttpGet]
public string Method( int a)
{
return "";
}

Got HTTP 405 error is this examples

 [HttpPut]
         public string Method([FromBody] int a)
         {
         }

没有错误,但参数 a 是 0..

 [HttpGet]
         public string Method([FromBody] int a)
         {
             return a.ToString();
         }

换句话说..使用 [HttpPut] 或使用未定义或定义为 [FromUri] 的参数不起作用。

仅适用于 [HttpGet] 和 [FromBody],但参数为空。

我的 WebApiConfig 看起来像这样

 public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
           
        }

为什么它不起作用?

【问题讨论】:

    标签: asp.net-web-api http-post http-get frombodyattribute


    【解决方案1】:

    您必须在控制器方法中命名参数,因为它们在路由配置中命名。所以,要么将其命名为id

    [HttpPut]
    public string Method(int id)
    {
    return "";
    }
    
    [HttpGet]
    public string Method(int id)
    {
    return "";
    }
    

    ...或者,在路由配置中更改它:

     public static void Register(HttpConfiguration config)
     {
         config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{action}/{a}",
             defaults: new { a = RouteParameter.Optional }
         );
    
     }
    

    请注意,它现在配置为 a 而不是 id

    更新

    以下是适用于上述配置的路由的控制器方法:

    // Example URI: http://localhost:62536/api/Controller/PutMethod/10
    [HttpPut]
    public string PutMethod(int a)
    {
    return a.ToString();
    }
    
    // Example URI: http://localhost:62536/api/Controller/GetMethod/10
    [HttpGet]
    public string GetMethod(int a)
    {
    return a.ToString();
    }
    
    // Example URI: http://localhost:62536/api/Controller/PutMethod/
    [HttpPut]
    public string PutMethod()
    {
    return "(none)";
    }
    
    // Example URI: http://localhost:62536/api/Controller/GetMethod/
    [HttpGet]
    public string GetMethod()
    {
    return "(none)";
    }
    

    GET、PUT、POST、DELETE HTTP 动词的使用

    本质上,RESTful API 设计围绕着对业务/应用程序域建模的资源、寻址它们的 URI 以及 GET、PUT、POST、DELETE 四种基本操作(有时还有第 5 个,PATCH)。例如,在人力资源应用程序域中,我们有员工。我们可以将员工集合表示为由 URI http://example.com/api/Employees 寻址的资源,并将集合中的每个员工表示为由 URI http://example.com/api/Employee/id 寻址的资源,其中 id 是员工。所以,我们可以:

    如果路由配置如下:

     public static void Register(HttpConfiguration config)
     {
         config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",i
             defaults: new { id = RouteParameter.Optional }
         );
     }
    

    员工的控制者可能是:

    public class EmployeesController : ApiController
    {
        // GET api/Employees
        public IEnumerable<Employee> Get()
        {
            List<Employee> employees = null;
            // Get here the list of employees
            return employees;
        }
    
        // POST api/Employees
        public int Post(Employee employee)
        {
            // Persist here the new employee and determine its ID (for example, identity in SQL Server)
            return employee.Id;  // Returns the ID of the newly created employee
        }
    
        // GET api/Employees/5
        public Employee Get(int id)
        {
            Employee employee;
            // Get here the employee with the id
            return employee;
        }
    
        // PUT api/Employees/5
        public Employee Put(int id, Employee employee)
        {
            var updatedEmployee;
            // Find existing employee with the id, update it with the data passed via employee argument and persist it
            return updatedEmployee;  // It's a good practice to return the updated entity back, especially in the case when updating changes some properties, e.g. summarized values, counts, etc.
        }
    
        // DELETE api/Employees/5
        // More complicated example showing communicating statuses back to the client regarding successfulness of the operation
        public IHttpAction Delete(int id)
        {
            Employee employee;
            // Find the employee with the id
            if (employee == null)
                return NotFound();  // The employee is not found. Signal 404, i.e. there's no resource at this URI.
            // Delete here the employee from the persistence mechanism
            return Ok();  // The employee is found and deleted. Signal 200 - OK
        }
    }
    

    请注意,不需要[HttpGet][HttpPut] 等属性。这一切都按惯例工作。

    当然,这是一个过于简单化的例子,只是为了传达这一点。

    希望对你有帮助。

    【讨论】:

    • 我将 Method(int a) 替换为 Method(int id) 它部分有效.. 仅使用 HTTGet... 和 Method(int) 或 Method([FromUri] .. 当我使用 [FromBody ] 为空.. 使用 HttpPost 时给了我错误 405... 这个结果是正确的吗?谢谢
    • 你想如何发送它,通过 URL 还是通过请求正文?当它是值类型(如 int)时,按照惯例,参数取自 URL,无需指定 [FromUri]。如果指定了 [FromBody],则应在请求正文中发送它。最简单的方法是通过 URL 传递它。通过请求正文,您必须将其作为 XML、JSON 等发送。
    • 再次感谢!!!.. 最后一个问题... 我什么时候应该使用 HttpPost?因为它总是适用于 HttpGet...
    • Pues,我更新了答案,简单解释了何时以及如何使用各种 HTTP 动词。希望你会发现它有帮助。 :)
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多