2012-10-16 42 views
2

我真的得到這個錯誤的非可空類型參數「ID」無效項,當我試圖通過HTTP URL發佈一些命令詞典共包含「System.Int32」

參數字典包含 不可爲空的類型'System.Int32'的參數'id'的空條目 'DatabaseService_WebAPI.Models.Product GetProduct(Int32)'的 'DatabaseService_WebAPI.Controllers.ProductController'。可選 參數必須是參考類型,可爲空類型,或者聲明爲可選參數 。

我使用ASP.NET Web API上可用的教程製作了我的api控制器。

這是我的網址

http://localhost:3325/api/Product/PostProduct?User=Haris2&ShopName=Dwatson&city=RYK&OrderDate=28/9/2012&OrderDetail=Strips 

Product.cs

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Web; 

namespace DatabaseService_WebAPI.Models 
{ 
    public class Product 
    { 
     [ScaffoldColumn(false)] 
     public int Id { get; set; } 
     [Required] 
     public string User { get; set; } 
     public string ShopName { get; set; } 
     public string city { get; set; } 
     public string OrderDate { get; set; } 
     public string OrderDetail { get; set; } 
    } 
} 

ProductController.cs

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.Entity; 
using System.Data.Entity.Infrastructure; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web; 
using System.Web.Http; 
using DatabaseService_WebAPI.Models; 

namespace DatabaseService_WebAPI.Controllers 
{ 
    public class ProductController : ApiController 
    { 
     private ProductContext db = new ProductContext(); 

     // GET api/Product 
     public IEnumerable<Product> GetProducts() 
     { 
      return db.Products.AsEnumerable(); 
     } 

     // GET api/Product/5 
     public Product GetProduct(int id) 
     { 
      Product product = db.Products.Find(id); 
      if (product == null) 
      { 
       throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); 
      } 

      return product; 
     } 

     // PUT api/Product/5 
     public HttpResponseMessage PutProduct(int id, Product product) 
     { 
      if (ModelState.IsValid && id == product.Id) 
      { 
       db.Entry(product).State = EntityState.Modified; 

       try 
       { 
        db.SaveChanges(); 
       } 
       catch (DbUpdateConcurrencyException) 
       { 
        return Request.CreateResponse(HttpStatusCode.NotFound); 
       } 

       return Request.CreateResponse(HttpStatusCode.OK); 
      } 
      else 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest); 
      } 
     } 

     // POST api/Product 
     public HttpResponseMessage PostProduct(Product product) 
     { 
      if (ModelState.IsValid) 
      { 
       db.Products.Add(product); 
       db.SaveChanges(); 

       HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product); 
       response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.Id })); 
       return response; 
      } 
      else 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest); 
      } 
     } 

     // DELETE api/Product/5 
     public HttpResponseMessage DeleteProduct(int id) 
     { 
      Product product = db.Products.Find(id); 
      if (product == null) 
      { 
       return Request.CreateResponse(HttpStatusCode.NotFound); 
      } 

      db.Products.Remove(product); 

      try 
      { 
       db.SaveChanges(); 
      } 
      catch (DbUpdateConcurrencyException) 
      { 
       return Request.CreateResponse(HttpStatusCode.NotFound); 
      } 

      return Request.CreateResponse(HttpStatusCode.OK, product); 
     } 

     protected override void Dispose(bool disposing) 
     { 
      db.Dispose(); 
      base.Dispose(disposing); 
     } 
    } 
} 

RouteConfig.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Routing; 

namespace DatabaseService_WebAPI 
{ 
    public class RouteConfig 
    { 
     public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

      routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 

      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 
     } 
    } 
} 

的Global.asax

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 
using DatabaseService_WebAPI.App_Start; 

namespace DatabaseService_WebAPI 
{ 
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801 

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     System.Data.Entity.Database.SetInitializer(new DatabaseService_WebAPI.Models.ProductContextInitializer()); 

     // WebApiConfig.Configure(GlobalConfiguration.Configuration); 

     AreaRegistration.RegisterAllAreas(); 

     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
    } 
} 

}

是我調用的方法是錯誤的或我必須做別的東西跳過ID?

+1

您是否稱過api/Product/5或api/Product?如果前者,那麼所需的ID顯然爲空,所以錯誤是正確的 –

+1

嘗試更改公共產品GetProduct(int id){}公共產品GetProduct(int?id){} – MMK

+0

@MohsenAfshin我叫做api/Product/PostProduct @MMK我沒有得到產品。我試圖發佈產品。 – Haris

回答

1

兩件事情:

  1. ,如果你想通過你需要[FromUri]在您的產品參數來自Url的這種複雜類型:

    // POST api/Product 
    public HttpResponseMessage PostProduct(Product product) 
    {...} 
    
  2. 您需要添加,在烏里接受動作的名稱一個Http路線(因爲你的URI你在它提供了「PostProduct」 ...)

    config.Routes.MapHttpRoute(
         name: "DefaultApi", 
         routeTemplate: "api/{controller}/{action}/{id}", 
         defaults: new { id = RouteParameter.Optional } 
        ); 
    
+0

[FromUri]工作很好。但是當我添加{action}時,它給了我一個不好的請求響應。反正thx爲你的答案。 – Haris

2

嘗試添加以下屬性[FromUri]到您的POST方法:

// POST api/Product 
    public HttpResponseMessage PostProduct([FromUri]Product product) 
    { 

你的相對URL應該是

http://localhost:xxxx/api/Product 

這應該允許您使用這個網址來發表您的模型:

http://localhost:xxxx/api/Product?User=Haris2&ShopName=Dwatson&city=RYK&OrderDate=28/9/2012&OrderDetail=Strips 

Also consi明鏡使用JSON [FromBody]有效載荷來代替:

// POST api/Product 
    public HttpResponseMessage PostProduct([FromBody]Product product) 
    { 

有了這樣的要求:

User-Agent: Fiddler 
Host: localhost:55805 
Content-Length: 98 
Content-Type: application/json 

POST: http://localhost:xxxx/api/product 

BODY: {"User":"Haris2","ShopName":"Dwatson","city":"RYK","OrderDate":"28/9/2012","OrderDetail":"Strips"} 
+0

Thx很多Mark Jones。這是完美的。 – Haris

-2

您必須添加表單方法操作鏈接

@Html.ActionLink("عرض التفاصيل", "JobDetails","Job", new { id = item.UniqueId },***FormMethod.Get or post***) 
相關問題