web api 跨域
最近接到一个关于webapi 挂到iis服务器的工作任务,通过上网学习特来跟大加分享一下;
首先配置wenapi如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using wete.Models;
namespace wete.Controllers
{
public class EmployeesController : ApiController
{
static List<Employees> emps;
static EmployeesController()
{
emps = new List<Employees>();
emps.Add(new Employees { Id = 1, DepartmentId = 1, Name = "张三", Gender = "男", Job = "工程师", PhoneNum = "10086", EmailAdderss = "123@123.com", Address = "xxxx" });
emps.Add(new Employees { Id = 2, DepartmentId = 2, Name = "李四", Gender = "女", Job = "工程师", PhoneNum = "10086", EmailAdderss = "456@123.com", Address = "ccccc" });
}
public IEnumerable<Employees> Get(int? id = null)
{
return from employee in emps where employee.Id.Equals(id) || string.IsNullOrEmpty(Convert.ToString(id)) select employee;
}
public void Post(Employees employee)
{
employee.Id = 3;
emps.Add(employee);
}
public void Put(Employees employee)
{
emps.Remove(emps.Where(e => e.Id == employee.Id).First());
emps.Add(employee);
}
public void Delete(int id)
{
emps.Remove(emps.Where(e => e.Id == id).FirstOrDefault());
}
public string Options()
{
return null; // HTTP 200 response with empty body
}
}
}
然后点击项目进行发布
配置好相应的路径,然后我们打开iis服务器
选择网站右键单击添加网站
配置完成后点击确定,下面来测试下是否配置成功
上传成功,下面来调用webapi接口;调用之前先在发布网站的根目录下的webconfg进行修改
添加如下代码即可调用跨域
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
weinform后台代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Net.Http;
namespace WindowsFormsApi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Uri url = new Uri("http://192.168.0.135/api/TestUser/");
private Uri url2 = new Uri("http://192.168.0.135/api/values");
public void databind()
{
using (WebClient client = new WebClient())
{
client.Headers["Type"] = "GET";
client.Headers["Accept"] = "application/json";
client.Encoding = Encoding.UTF8;
client.DownloadStringCompleted += (senderobj, es) =>
{
if (es.Result != null)
{
//List<Student> users = JsonConvert.DeserializeObject<List<Student>>(es.Result);
//var test = JsonConvert.DeserializeObject<Student[]>(es.Result);
//MessageBox.Show(users.ToString());
//dataGridView1.DataSource = users;
List<Student> list = JsonConvert.DeserializeObject<List<Student>>(es.Result);
int i = 0;
foreach (Student zr in list)
{
int id = Convert.ToInt32(zr.id);
string sex = zr.sex;
string name = zr.stuname;
int age = zr.age;
this.dataGridView1.Rows.Add();
//this.dataGridView1["column2", i].Value = name;
//this.dataGridView1["column3", i].Value = zwjyzsbh;
//this.dataGridView1["column4", i].Value = zwmc;
this.dataGridView1.Rows[i].Cells[0].Value = id;
this.dataGridView1.Rows[i].Cells[1].Value = name;
this.dataGridView1.Rows[i].Cells[2].Value = sex;
this.dataGridView1.Rows[i].Cells[3].Value = age;
i++;
}
}
};
client.DownloadStringAsync(url);
}
}
private async void button1_Click(object sender, EventArgs e)
{
Student people = new Student();
people.id = 15;
people.stuname = textBox1.Text.ToString();
people.sex = textBox2.Text.ToString();
people.age = Convert.ToInt32(textBox3.Text.ToString());
string data = JsonConvert.SerializeObject(people);
//创建一个处理序列化的DataContractJsonSerializer
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Student));
MemoryStream ms = new MemoryStream();
ms.Seek(0, SeekOrigin.Begin);
serializer.WriteObject(ms, people);
//一定要在这设定Position
ms.Position = 0;
HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
//一定要设定Header
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
//由HttpClient发出Post Method
HttpResponseMessage response = await client.PostAsync(url2, content);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("成功");
databind();
}
else
{
MessageBox.Show("未进行身份验证");
}
}
private void button4_Click(object sender, EventArgs e)
{
databind();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private async void button2_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
//由HttpClient发出Delete Method
HttpResponseMessage response = await client.DeleteAsync(url + "/1");
if (response.IsSuccessStatusCode)
{
MessageBox.Show("成功");
databind();
}
}
private async void button3_Click(object sender, EventArgs e)
{
//创建一个处理序列化的DataContractJsonSerializer
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Student));
MemoryStream ms = new MemoryStream();
//将资料写入MemoryStream
serializer.WriteObject(ms, new Student() { id = 1, stuname = "Hello ni", sex = "boy", age = 18 });
//一定要在这设定Position
ms.Position = 0;
HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
//由HttpClient发出Put Method
HttpResponseMessage response = await client.PutAsync(url + "/1", content);
if (response.IsSuccessStatusCode)
{
MessageBox.Show("成功");
databind();
}
}
}
public class Student
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("stuname")]
public string stuname { get; set; }
[JsonProperty("age")]
public int age { get; set; }
[JsonProperty("stusex")]
public string sex { get; set; }
}
}
成功后的结果如下
第一次写博客不知怎么写希望大家能提点意见