今天用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")]
三、完整測試代碼
樹立目标,保持活力,gogogo!