我在asp.net mvc中创建了web api。我想要的是在asp.net中从另一个项目(网站)调用web api中的post方法。
这是我的班级供应商
[ModelBinder(typeof(VendorModelBinder))]
public class Vendor
{
public string VenName { get; set; }
public string VenCompany { get; set; }
}
这是VendorModelBinder
public class VendorModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(Vendor))
{
return false;
}
Vendor result = JsonConvert.DeserializeObject<Vendor>
(actionContext.Request.Content.ReadAsStringAsync().Result);
bindingContext.Model = result;
return true;
}
这是我的VendorController
public class VendorController : ApiController
{
// POST: api/Vendor/5
[HttpPost]
[Route("")]
public HttpResponseMessage Post([ModelBinder]Vendor Ven)
{
SqlConnection con = new SqlConnection(" Data Source = DELL; Initial Catalog = EVENT; Integrated Security = True");
SqlCommand com = new SqlCommand("[dbo].[InsVendor]", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@user", Ven.VenName);
com.Parameters.AddWithValue("@compnay", Ven.VenCompany);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
HttpResponseMessage message = Request.CreateResponse(HttpStatusCode.OK);
message.Content = content;
return message;
}
}
这里我在web api中调用post方法
static async Task<Uri> AddVendorAsync(AllVendor Ven)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56908/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent content = new StringContent(JsonConvert.SerializeObject(Ven), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("api/Vendor", content);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
// return URI of the created resource.
return response.Headers.Location;
}
}
以上程序是否正确? 因为我在供应商控制器(Ven.VenName)
获取空对象请帮助我。 感谢。