• Message": "请求的资源不支持 http 方法“GET”


    今天用postman测试后端api,总是报错,下面是问题解决方案。

    一、测试方法

    public ApiResult Get(int id)
    {
    ApiResult result = new ApiResult();

    result.data = "我是Get方法返回的数据";
    result.success = true;
    result.msg = "测试成功";

    return result;
    }

    public class ApiResult
    {
    public bool success { get; set; }

    public string msg { get; set; }

    public object data { get; set; }
    }

    二、问题和解决

    0请求:http://localhost/projectmanagement/api/user/5

    在网上查了下请求要这么写:http://localhost/projectmanagement/api/user/?id=5

    1 提示没有权限

    去路由里面一看,前辈重新了校验规则,不知道。为了测试方法我注释的校验规则。

    public static void Register(HttpConfiguration config)
    {
    // Web API 配置和服务

    // Web API 路由
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );
    // config.Filters.Add(new AppAuthorizeAttribute());

    }

    2   "Message": "请求的资源不支持 http 方法“GET”。"

    请求 

    解决:在方法代码上一行 添加 [HttpGet]

    3 又报 "Message": "请求的资源不支持 http 方法“GET”。"

    解决:同时在多个方法代码 添加 [HttpGet],必须取别名 ,例如 [Route("Get")]  

    请求也要加别名:http://localhost/projectmanagement/api/user/get/?id=5

    http://localhost/projectmanagement/api/user/First/?id=5

    然后还是报错。

    解决:使用别名时,必须在控制器类上面加前缀    [RoutePrefix("api/User")]

    三、完整测试代码

    using ProjectManagement.BLL;
    using ProjectManagement.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace ProjectManagement.Controllers
    {
        [RoutePrefix("api/User")]
        public class UserController : ApiController
        {
         
            [HttpGet]
            [Route("First")]  
            public ApiResult First(int id)
            {
                ApiResult result = new ApiResult();
    
                result.data = "我是First方法返回的数据";
                result.success = true;
                result.msg = "测试成功";
    
                return result;
            }
    
            [HttpGet]
            [Route("Get")]
            public ApiResult Get(int id)
            {
                ApiResult result = new ApiResult();
    
                result.data = "我是Get方法返回的数据";
                result.success = true;
                result.msg = "测试成功";
    
                return result;
            }
    
        }
    }
    

      

  • 相关阅读:
    IIS与ASP.NET管道
    20个非常棒的jQuery倒计时脚本
    GitHub托管BootStrap资源汇总(持续更新中…)
    推荐13款优秀的Twitter Bootstrap JavaScript插件
    C#程序开发中经常遇到的10条实用的代码
    20款jQuery 的音频和视频插件
    给 C# 开发者的代码审查清单
    Bootstrap 3.0正式版发布!
    为你带来灵感的 20 个 HTML5/CSS3 模板
    通过一个模拟程序让你明白ASP.NET MVC是如何运行的
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/9765918.html
Copyright © 2020-2023  润新知