如何在路线中包含区域

时间:2015-12-31 15:06:08

标签: asp.net-web-api2 asp.net-web-api-routing

我的WebApiConfig

中有以下内容
 public static void Register(HttpConfiguration config)
 {           
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));           
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",                                
            defaults: new { id = RouteParameter.Optional }
        );
        var cors = new EnableCorsAttribute("http://localhost:15880", "*", "*");
        config.EnableCors(cors);
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

    }

现在在ProductAreaRegistration中

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.Routes.MapHttpRoute(
            name: this.AreaName,                
           routeTemplate: "api/" + this.AreaName + "/{controller}/{id}",
            defaults: new { id = UrlParameter.Optional }
            );
        context.MapRoute(
            "Product_default",
            "Product/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }                
        );
    }

现在我的WebApi控制器中有以下内容..

public IHttpActionResult GetProduct()
    {
        try
        {
            var product = db.Products.Take(5);
            if (product == null)
            {
                return NotFound();
            }
            else
            {
                return Ok(product );
            }
        }
        catch(Exception ex)
        {
            return InternalServerError(ex);
        }

    }

    public IHttpActionResult GetProduct(long id)
    {
        try 
        {
            var product = db.Products.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            return Ok(product );
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

现在我在这里尝试提出请求

http://localhost:15877/Api/PT/GetProducts/1 it successfully get invoked

Get Method with parameter以及我说

http://localhost:15877/Api/GetProducts/1 it works fine 

当我说

http://localhost:15877/Api/GetProducts it gets me list of Products and when I say

http://localhost:15877/Api/PT/GetProducts it says
{"$id":"1","Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of...

我有什么遗失的东西。我的基本想法是通过传递区域名称获取列表或单个对象,此处PT是区域。你能告诉我,当我说

时,我该怎么做才能使它运作起来
http://localhost:15877/Api/PT/GetProducts 

感谢。

0 个答案:

没有答案