Creating a WebService inside my MVC project

こ雲淡風輕ζ 提交于 2019-12-25 03:05:36

问题


I know there's another thread about WebapiConfig.cs and RouteConfig.cs, but I can assure this is a different question.

My MVC project was quite developed by the time I found out I would have to create a webservice (in the same domain) where I would grant access to one of my models (both in JSON and XML).

In order to do so, I right clicked over my Controllers and selected "add Web API 2 Controller with actions, using Entity Framework" and selected also my model class and db context.

The template was quite complete and I thought I was ready to go for the following test:

namespace MVC4GMAPS.Controllers
{
    public class RestController : ApiController
    {
        private LocationDBContext db = new LocationDBContext();

        // GET api/Rest
        public IQueryable<Location> GetLocations()
        {
            return db.Locations;
        }
etc...

Unfortunately, when I tried to access to https://localhost:44300/api/Rest I've got a 404. However, localhost:44300/Home/Index keeps working great.

I believe the problem relies on my RouteConfig.cs, because it is expecting an {action} and my RestController doesn't have any actions:

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 }
            );
etc...

What can I do? Can I create simultaneously a WebapiConfig.cs file? I believe not. I hope you can help me!


回答1:


Do you also have a WebApiConfig.cs? In a project which was "Web API from the start" I have this in it:

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 }
    );
  }
}

This, like the other configs, is called from Global.asax.cs:

GlobalConfiguration.Configure(WebApiConfig.Register);

That should get the routing pointed to the API controller. Otherwise, as you say, the route defined from MVC by default would be looking for an action called Rest on a controller called api which doesn't exist.



来源:https://stackoverflow.com/questions/22385083/creating-a-webservice-inside-my-mvc-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!