【问题标题】:The requested resource does not support http method 'GET' when calling action returning boolean调用返回布尔值的操作时,请求的资源不支持 http 方法“GET”
【发布时间】:2016-01-12 15:32:17
【问题描述】:

我有一个 Web API,其中控制器中有多个 get 方法。控制器方法之一返回 true 或 flas - 用作员工 ID 的验证

下面是我的代码:

我的存储库类:

public class myRepository
{

    public myClasses.Type[] GetAllTypes()
    {

        return new myClasses.Type[]
        {
            new myClasses.Type 
            {
                typeId="1",
                typeVal = "New"
            },
            new myClasses.Type 
            {
                typeId="2",
                typeVal = "Old"
            }
       };

    }

    public myClasses.Employee[] GetAllEmployees()
    {

        return new myClasses.Employee[]
        {
            new myClasses.Employee 
            {
                empId="111111",
                empFName = "Jane",
                empLName="Doe"
            },
            new myClasses.Employee 
            {
                empId="222222",
                empFName = "John",
                empLName="Doe"
            }
       };

    }

    public bool VerifyEmployeeId(string id)
    {

        myClasses.Employee[] emp = new myClasses.Employee[]
        {
            new myClasses.Employee 
            {
                empId="111111",
                empFName = "Jane",
                empLName="Doe"
            },
            new myClasses.Employee 
            {
                empId="222222",
                empFName = "John",
                empLName="Doe"
            }
       };

        for (var i = 0; i <= emp.Length - 1; i++)
        {
            if (emp[i].empId == id)
                return true;
        }
        return false;
    }
}

和我的模型类:

public class myClasses
{

    public class Employee
    {
        public string empId { get; set; }
        public string empFName { get; set; }
        public string empLName { get; set; }
    }

    public class Type
    {
        public string typeId { get; set; }
        public string typeVal { get; set; }
    }
}

这是我的控制器:

public class myClassesController : ApiController
{
    private myRepository empRepository;

    public myClassesController()
    {
        this.empRepository = new myRepository();
    }

    public myClasses.Type[] GetTypes()
    {
        return empRepository.GetAllTypes();
    }

    public myClasses.Employee[] GetEmployees()
    {
        return empRepository.GetAllEmployees();
    }

    public bool VerifyEmployee(string id)
    {
        return empRepository.VerifyEmployeeId(id);
    }
}

一切都编译得很好,但是当我使用它运行它时

http://localhost:49358/api/myClasses/GetTypes

并以 xml 格式返回所有数据。但是当我跑步时

http://localhost:49358/api/myClasses/VerifyEmployee/222222

我收到错误“请求的资源不支持 http 方法 'GET'”

我的 WebAPIConfig:

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

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
    }
}

谁能指出我正确的方向?我在这里做错了什么?有没有更好的方法通过 Web API 对数据进行验证?

【问题讨论】:

    标签: c# model-view-controller asp.net-web-api


    【解决方案1】:

    在我看来,你不需要只创建一个 Action 来验证你的 Employee,当你想对这个 Employee 做任何更改时,你可以在这个 Action 中验证它,这样你就可以节省 1 个额外的请求,例如:

    [HttpPut]
    public IHttpActionResult Update(EmployeeViewModel model)
    {
        if(!empRepository.VerifyEmployeeId(model.Id))
            return BadRequest("Some error message");
    
        empRepository.Update(model);
        return Ok();
    }
    

    在您的返回类型中,您应该使用IHttpActionResult 来使用Http 状态码。除非您需要返回 Collection。

    如果您需要一个操作来仅验证员工,无论出于何种原因,您都可以这样做:

    [HttpGet]
    public IHttpActionResult VerifyEmployee(string id)
    {
        var isValid = empRepository.VerifyEmployeeId(string id);
    
        return isValid ? Ok() : BadRequest("Some message");
    }
    

    如果您使用的是 WebApi 版本 1,请尝试以下操作:

    [HttpPut]
    public HttpResponseMessage Update(EmployeeViewModel model)
    {
        if(!empRepository.VerifyEmployeeId(model.Id))
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
    
        empRepository.Update(model);
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
    [HttpGet]
    public HttpResponseMessage VerifyEmployee(string id)
    {
        var isValid = empRepository.VerifyEmployeeId(string id);
    
        return isValid ? new HttpResponseMessage(HttpStatusCode.OK) : new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
    

    【讨论】:

    • 我不能使用第一个示例,因为我没有进行更新,只是检查 id 是否有效。至于第二个例子,你能解释一下为什么是 IHttpActionRequest 吗?我还收到一个错误,即找不到命名空间 IHttpActionRequest
    • 您使用的是哪个版本的 WebApi? IHttpActionResult,带有自定义的内置响应,例如(Ok、BadRequest、NotFound、Unauthorized、Exception、Conflict、Redirect),带有自定义协商内容,并且仍然简化了控制器的单元测试。
    • 我使用的是版本 4
    • 您应该在开发者工具中看到(如果您使用的是 chrome),它会返回什么
    • 我使用的是 IE。如何使用 Chrome 打开 web api?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2014-01-28
    • 2015-10-08
    • 2013-07-31
    • 2017-10-17
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多