記第一次用mvc寫後臺接口

以前一直在寫前端,在習慣了後臺提供接口以後,我在新公司須要一我的獨自開發整個項目,這就不得不學着本身給本身寫接口,網上關於這樣的帖子比比皆是,借鑑了不少打算本身整理一份記錄下來。前端


  1. 打開VS 新建項目(用的VS2017社區版)

clipboard.png

clipboard.png

這裏選擇MVC 若是要用到Web API的路由,能夠勾選,身份驗證什麼的暫且不談先不驗證。web

clipboard.png

這是項目結構數據庫

  1. 添加控制器,我這裏選擇的是webAPI

clipboard.png

clipboard.png

先新建一個User的控制器跨域

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace mvcDemo.Controllers
{
    public class UserController : ApiController
    {
    }
}

這是控制器中的代碼,固然咱們確定要操做數據庫,因此咱們再新建一個LINQ文件mvc

clipboard.png

建立成功以後還須要建立一個數據庫connectionStringpost

clipboard.png

將數據表拖入LINQ文件中spa

clipboard.png

如今開始寫UserControlercode

using mvcDemo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace mvcDemo.Controllers
{
    public class UserController : ApiController
    {
        UserDataContext dc = new UserDataContext();
        [HttpGet]
        public Resp getUser(int id)
        {
            Resp resp = new Resp();
            List<User> list = new List<User>();
            list = dc.User.Where(x => x.Id == id).ToList();
            resp.Code = 200;
            resp.Data = list;
            resp.Message = "查詢成功";
            return resp;
        }

        [HttpPost]
        public Resp addUser(User user)
        {
            Resp resp = new Resp();
            User item = new User();
            item.Name = user.Name;
            item.Age = user.Age;
            item.Address = user.Address;
            dc.User.InsertOnSubmit(item);
            dc.SubmitChanges();
            resp.Code = 200;
            resp.Data = null;
            resp.Message = "添加成功";
            return resp;
        }
    }

    public class Resp
    {
        public int Code { get; set; }
        public List<User> Data { get; set; }
        public string Message { get; set; }
    }
}

這裏提供了兩個接口 一個是根據id查詢用戶,第二個是添加用戶。如今能夠運行程序,用postman 發送請求發現跨域還沒實現,因此要在web.config的system.webServer節點中添加代碼blog

<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>

若是涉及到options請求405的問題。
嘗試刪除web.config中<remove name="OPTIONSVerbHandler" />
而且在global.asax中添加接口

protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.End();
        }
    }

好了 如今就能夠跨域了~ 完成

相關文章
相關標籤/搜索