use*_*519 16 c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api
我试图在同一个项目中使用MVC控制器和WebAPI控制器,但我得到了webapi的404错误.我在vs 2015中开始作为MVC项目的项目,但后来添加了webapi控件,并且使用默认代码,它给出了404错误
什么是可能的解决方案.我已经在Stackoverflow上尝试了一些解决方案,但是他们没有工作,其中一个是下面的链接(那里的接受的答案) 所有ASP.NET Web API控制器返回404
Global.ASAX文件代码:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);//WEB API 1st
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Run Code Online (Sandbox Code Playgroud)
WEBAPI.CONFIG文件
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Run Code Online (Sandbox Code Playgroud)
路由配置文件代码
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Run Code Online (Sandbox Code Playgroud)
WebAPI控制器代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using O365_APIs_Start_ASPNET_MVC.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using O365_APIs_Start_ASPNET_MVC.Helpers;
using System.Threading.Tasks;
namespace O365_APIs_Start_ASPNET_MVC.Controllers
{
public class MAILAPIController : ApiController
{
private MailOperations _mailOperations = new MailOperations();
//async Task<BackOfficeResponse<List<Country>>>
// GET: api/MAILAPI
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/MAILAPI/5
public string Get(int id)
{
return "value";
}
// POST: api/MAILAPI
public void Post([FromBody]string value)
{
}
// PUT: api/MAILAPI/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/MAILAPI/5
public void Delete(int id)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
在同一解决方案中获取NUGET RESTORE ERROR 错误Nuget无法恢复PNG
Den*_*els 25
在注册MVC的路由之前,你需要注册web api 的路由,所以基本上你的App_Start()
函数应该是这样的:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);//WEB API 1st
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);//MVC 2nd
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14780 次 |
最近记录: |