3

当我尝试通过 HTTP URL 发布一些订单时出现此错误

参数字典包含“DatabaseService_WebAPI.Controllers.ProductController”中方法“DatabaseService_WebAPI.Models.Product GetProduct(Int32)”的不可空类型“System.Int32”的参数“id”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。

我使用 ASP.NET Web API 上提供的教程制作我的 api 控制器。

这是我的网址

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

产品.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; }
    }
}

产品控制器.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);
        }
    }
}

路由配置.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 }
            );
        }
    }
}

全球.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?

4

3 回答 3

2

尝试将以下属性添加[FromUri]到您的 POST 方法中:

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

您的相对 URL 应该是

http://localhost:xxxx/api/Product

这应该允许您使用此 URL 发布您的模型:

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

还可以考虑使用 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"}
于 2012-10-16T15:53:51.653 回答
2

两件事情:

  1. 如果要从 Url 传递此复杂类型,则需要在 Product 参数上使用 [FromUri]:

    // POST api/Product
    public HttpResponseMessage PostProduct(Product product)
    {...}
    
  2. 您需要在 Uri 中添加一个接受操作名称的 Http 路由(因为您提供的 uri 中包含“PostProduct”...)

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    
于 2012-10-16T16:03:30.487 回答
-3

您必须在操作链接中添加表单方法

 @Html.ActionLink("عرض التفاصيل", "JobDetails","Job",  new { id = item.UniqueId },***FormMethod.Get or post***)
于 2016-12-08T14:04:54.413 回答