在 Web API MVC 4 中找不到资源错误
本文关键字:找不到 资源 错误 Web API MVC | 更新日期: 2023-09-27 17:56:05
我的 web api 看起来可以工作,它以 json 格式分发数据
http://localhost:60783/api/employee/GetEmployeeList/
但是当我尝试指出.cshtm文件时,它会给我:
The resource cannot be found error .
我的路由配置看起来像这样
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
和我的网络ApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
my Global.asax :
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
我有一个名为EmployeeController
的控制器我使用
public async Task<ActionResult> Index()
{
HttpResponseMessage response = await ServiceAccess.Get("Employee/GetEmployeeList", null);
if (response.IsSuccessStatusCode)
{
List<Employee> model = await ServiceAccess.DeserializeAs<List<Employee>>(response);
return View(model);
}
return Content("No Record");
}
public ActionResult EmployeeList()
{
return View();
}
服务访问类 :
public static HttpClient httpClient;
static ServiceAccess()
{
httpClient = new HttpClient();
httpClient.BaseAddress = GeneralConstants.ServiceBaseURI;
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async Task<T> DeserializeAs<T>(HttpResponseMessage SerializedResponse)
{
return JsonConvert.DeserializeObject<T>(await SerializedResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
}
//mis named the name should be GetMany
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async Task<HttpResponseMessage> GetAll(string uri)
{
HttpResponseMessage response = await httpClient.GetAsync(uri).ConfigureAwait(false);
return response;
}
和网络配置文件有这个
<add key="ServiceBaseURI" value="http://localhost:60783/api/" />
给我问题的LNK:
http://localhost:60783/Employee/EmployeeList/
任何帮助表示赞赏。
你的代码中几乎没有错误。如果你考虑并调试你的代码,你会得到答案。
- 您的 API 控制器名称
EmployeeController
和 MVC 控制器名称EmployeeController
相同。 - 您需要提供员工 API 的正确 URL,在您的情况下,它可能位于某个文件夹中,因为在一个控制器文件夹中,您无法创建两个具有相同名称的控制器(在您的情况下,您的 MVC 和 Web API 控制器名称似乎相同。
- 使用DHC或Postmen检查Web API方法,并检查您得到的响应,并在MVC控制器中使用相同的URL。