每当我试图执行下面的代码时,我都会遇到这个错误。正如我所检查的,我试图传递给控制器的参数为null。我真的不知道怎么解决这个问题。请帮帮忙。
错误: System.NullReferenceException未被用户代码处理
代码:
主计长:
public class VisitorController : ApiController
{
static readonly IVisitorRepository repository = new VisitorRepository();
[HttpGet]
public HttpResponseMessage PostVisitor(Visitor guest)
{
guest = repository.AddGuest(guest);
var response = Request.CreateResponse<Visitor(HttpStatusCode.Created, guest);
string uri = Url.Link("DefaultApi", new { id = guest.ID });
response.Headers.Location = new Uri(uri);
return response;
}
}型号:
public class Visitor
{
public int ID { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string Purpose { get; set; }
public string Location { get; set; }
public DateTime LoggedIn { get; set; }
public DateTime LoggedOut { get; set; }
}类:
public Visitor AddGuest(Visitor details)
{
string sp = "AddGuestDetails";
try
{
SqlConnection conn = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(sp, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = details.ID;
cmd.Parameters.Add("@VisitorName", SqlDbType.NVarChar).Value = details.Name;
cmd.Parameters.Add("@Company", SqlDbType.NVarChar).Value = details.Company;
cmd.Parameters.Add("@Contact", SqlDbType.NVarChar).Value = details.Contact;
cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = details.Email;
cmd.Parameters.Add("@Purpose", SqlDbType.NVarChar).Value = details.Purpose;
cmd.Parameters.Add("@Location", SqlDbType.NVarChar).Value = details.Location;
cmd.Parameters.Add("@LogIn", SqlDbType.NVarChar).Value = details.LoggedIn;
cmd.Parameters.Add("@LogOut", SqlDbType.NVarChar).Value = details.LoggedOut;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: '{0}'", ex);
}
return details;
}处决:
localhost/api/visitor/postvisitor/?>Name=Anna&Company=ABCD&Contact=5555&Email=anna@abcd.com&Purpose=Meeting&Location=Roces&Log>gedIn=07/18/2014%2010:00:00&LoggedOut=07/18/2014%2010:00:00}“
发布于 2014-07-21 05:45:49
您需要将来宾作为JSON传递到身体中。要么用Javascript写成这样。
http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods
或者使用您的邮递员工具发布JSON和url,下面不使用邮递员,但它非常相似.
http://www.agile-code.com/blog/building-an-asp-net-web-api-restful-service/
https://stackoverflow.com/questions/24857952
复制相似问题